var __reflect = (this && this.__reflect) || function (p, c, t) {
    p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
};
var __extends = this && this.__extends || function __extends(t, e) { 
 function r() { 
 this.constructor = t;
}
for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]);
r.prototype = e.prototype, t.prototype = new r();
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var d5;
(function (d5) {
    var Displayer = (function () {
        function Displayer() {
        }
        Object.defineProperty(Displayer.prototype, "monitor", {
            get: function () {
                return this._monitor;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Displayer.prototype, "parent", {
            get: function () {
                return this._monitor.parent;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Displayer.prototype, "position", {
            get: function () {
                return this._monitor.postion;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Displayer.prototype, "width", {
            get: function () {
                return this.realWidth;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Displayer.prototype, "height", {
            get: function () {
                return this.realHeight;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Displayer.prototype, "x", {
            get: function () {
                return this._monitor.x;
            },
            set: function (v) {
                this._monitor.x = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Displayer.prototype, "y", {
            get: function () {
                return this._monitor.y;
            },
            set: function (v) {
                this._monitor.y = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Displayer.prototype, "rotation", {
            set: function (v) {
                this._monitor.rotation = v;
            },
            enumerable: true,
            configurable: true
        });
        Displayer.prototype.remove = function () {
            this._monitor && this._monitor.parent && this._monitor.parent.removeChild(this._monitor);
        };
        Displayer.prototype.setPosition = function (px, py) {
            this.monitor.x = px;
            this.monitor.y = py;
        };
        Displayer.prototype.setRelativePostion = function (px, py, target) {
            this._fllow = target;
            this._rx = px;
            this._ry = py;
            this.setPosition(target.x + px, target.y + py);
        };
        Object.defineProperty(Displayer.prototype, "touchEnabled", {
            set: function (v) {
                this._monitor.eventMode = v ? 'static' : 'none';
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Displayer.prototype, "touchEnable", {
            set: function (v) {
                this._monitor.eventMode = v ? 'static' : 'none';
            },
            enumerable: true,
            configurable: true
        });
        Displayer.prototype.once = function (event, listener) {
            this._monitor.once(event, listener);
        };
        Displayer.prototype.addEventListener = function (event, listener, cursor) {
            if (cursor === void 0) { cursor = null; }
            this._monitor.on(event, listener);
            if (cursor != null) {
                this._monitor.cursor = cursor;
            }
        };
        Displayer.prototype.removeEventListener = function (event, listener) {
            if (listener === void 0) { listener = null; }
            if (listener) {
                this._monitor.off(event, listener);
            }
            else {
                this._monitor.off(event);
            }
        };
        Displayer.prototype.dispatchEvent = function (event, data) {
            if (data === void 0) { data = null; }
            this._monitor.emit(event, { type: event, data: data, target: this });
        };
        Displayer.prototype.dispathEvent = function (event, data) {
            if (data === void 0) { data = null; }
            this._monitor.emit(event, { type: event, data: data, target: this });
        };
        Displayer.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
        };
        Object.defineProperty(Displayer.prototype, "scale", {
            set: function (v) {
                this.monitor.scale.set(v);
            },
            enumerable: true,
            configurable: true
        });
        Displayer.prototype.setSize = function (w, h) {
            this.realWidth = w;
            this.realHeight = h;
        };
        return Displayer;
    }());
    d5.Displayer = Displayer;
    __reflect(Displayer.prototype, "d5.Displayer");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var DisplayContainer = (function (_super) {
        __extends(DisplayContainer, _super);
        function DisplayContainer() {
            var _this = _super.call(this) || this;
            _this._monitor = new PIXI.Container();
            _this._monitor.d5component = _this;
            return _this;
        }
        Object.defineProperty(DisplayContainer.prototype, "numChildren", {
            get: function () {
                return this.monitor.children.length;
            },
            enumerable: true,
            configurable: true
        });
        DisplayContainer.prototype.removeChildAt = function (index) {
            return this.monitor.removeChildAt(index);
        };
        DisplayContainer.prototype.setChildIndex = function (v, index) {
            this.monitor.setChildIndex(v.monitor, index);
        };
        DisplayContainer.prototype.addChild = function (displayer) {
            this._monitor.addChild(displayer.monitor ? displayer.monitor : displayer);
            return displayer;
        };
        DisplayContainer.prototype.removeChild = function (displayer) {
            this._monitor.removeChild(displayer.monitor ? displayer.monitor : displayer);
            return displayer;
        };
        DisplayContainer.prototype.removeChildren = function () {
            this._monitor.removeChildren();
        };
        DisplayContainer.prototype.getChildAt = function (index) {
            return index < this.numChildren ? this._monitor.getChildAt(index).d5component : null;
        };
        /**
         * 将与自己同容器，且在自己范围内的对象纳入自己的自对象，形成一个整体
         *
         * @param   e
         * @param   skip    不进行合并的对象
         * @param   contain 必然进行合并的对象
         */
        DisplayContainer.prototype.add2Me = function () {
            var contain = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                contain[_i] = arguments[_i];
            }
            for (var i = 0, j = contain.length; i < j; i++) {
                var obj = contain[i];
                obj.setPosition(obj.x - this.x, obj.y - this.y);
                this.addChild(obj);
            }
        };
        return DisplayContainer;
    }(d5.Displayer));
    d5.DisplayContainer = DisplayContainer;
    __reflect(DisplayContainer.prototype, "d5.DisplayContainer");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5Component = (function (_super) {
        __extends(D5Component, _super);
        function D5Component() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        D5Component.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            this._initArgs = args;
        };
        D5Component.prototype.remove = function () {
            _super.prototype.remove.call(this);
            if (this._waitTime > 0)
                clearTimeout(this._waitTime);
            this._waitTime = 0;
        };
        D5Component.prototype.clone = function () {
            throw new Error("[D5Component] this component can not be clone");
        };
        D5Component.prototype.asyncDraw = function (timeout) {
            var _this = this;
            if (timeout === void 0) { timeout = 30; }
            if (this._waitTime > 0)
                return;
            this._waitTime = setTimeout(function () {
                _this.draw();
                _this._waitTime = 0;
            }, timeout);
        };
        D5Component.prototype.draw = function () {
        };
        D5Component.getComponentByJSON = function (res, obj, container) {
            var arr = obj.uiList;
            var length = arr.length;
            var comObj;
            var uiObj;
            var src;
            var list = [];
            container.setFly(obj.flyx, obj.flyy);
            container.setSize(parseInt(obj.width), parseInt(obj.height));
            for (var i = 0; i < length; i++) {
                comObj = arr[i];
                uiObj = D5Component.getComponentByJson(comObj, container);
                src = comObj.file;
            }
        };
        D5Component.getComponentByJson = function (value, container) {
            var com;
            switch (value.Class) {
                case "D5Window":
                    com = new d5.D5Window();
                    com.name = value.name;
                    com.init(null, value.skinId, { x: parseInt(value.x1), y: parseInt(value.y1) }, { x: parseInt(value.x2), y: parseInt(value.y2) });
                    com.setSize(value.width, value.height);
                    break;
                case "D5MirrorBox":
                    com = new d5.D5MirrorBox();
                    com.name = value.name;
                    com.init(null, value.skinId, { x: parseInt(value.x1), y: parseInt(value.y1) }, { x: parseInt(value.x2), y: parseInt(value.y2) });
                    com.setSize(value.width, value.height);
                    break;
                case "D5MirrorLoop":
                    com = new d5.D5MirrorLoop();
                    com.name = value.name;
                    com.init(null, value.skinId, { mode: value.workmode, cut: value.cutsize }, parseInt(value.pin_position));
                    com.setSize(value.width, value.height);
                    break;
                case "D5Loop":
                    com = new d5.D5Loop();
                    com.name = value.name;
                    com.init(null, value.skinId, { x: parseInt(value.x), y: parseInt(value.y) }, parseInt(value.workmode), parseInt(value.pin_position));
                    com.setSize(value.width, value.height);
                    break;
                case "D5Bitmap":
                    com = new d5.D5Bitmap();
                    com.name = value.name;
                    com.init(null, value.skinId);
                    com.setSize(value.width, value.height);
                    break;
                case "D5Button":
                    com = new d5.D5Button();
                    com.name = value.name;
                    com.init(null, value.skinId);
                    com.setSize(value.width, value.height);
                    if (value.lable && value.lable != '') {
                        com.label = value.lable;
                    }
                    break;
                case "D5RadioBtn":
                    com = new d5.D5RadioBtn();
                    com.name = value.name;
                    com.init(null, value.skinId);
                    if (value.lable && value.lable != '') {
                        com.label = value.lable;
                    }
                    if (value.group != null && value.group != '')
                        com.groupName = value.group;
                    break;
                case "D5Text":
                    com = new d5.D5Text();
                    com.name = value.name;
                    com.init(value);
                    break;
                case "D5Shape":
                    com = new d5.D5Shape();
                    com.name = value.name;
                    com.pointString = value.pointString;
                    com.workMode = value.workMode;
                    com.drawAlpha = value.fillAlpha == null ? 1 : value.fillAlpha;
                    com.lineAlpha = value.tickNessAlpha == null ? 1 : value.tickNessAlpha;
                    com.setFillColor(value.fillColor);
                    com.setTickNess(value.tickNess);
                    com.setColor(value.color);
                    com.setOffX(value.offX);
                    com.setOffY(value.offY);
                    com.setSize(value.width, value.height);
                    com.setRadius(value.radius);
                    com.round = value.round;
                    com.rotation = value.rotation;
                    com.maskName = value.maskName;
                    break;
                default:
                    break;
            }
            if (com && container) {
                try {
                    container[value.name] = com;
                    com.ui = container;
                }
                catch (e) {
                    console.log("===can not bind " + value.name + "====\n" + e);
                }
            }
            else {
                console.log("[Warning] Can not init Class " + value.Class);
                return;
            }
            com && container.addChild(com);
            com.setPosition(value.x, value.y);
            var scalex = Number(value.scalex);
            var scaley = Number(value.scaley);
            if (!isNaN(scalex) && scalex != 1.0)
                com.scale = scalex;
            //if(!isNaN(scaley) && scaley!=1.0) com.scaleY = scaley;
            //com.moveAction = parseInt(value.moveAction);
            if (parseInt(value.margin_mode) > 0) {
                com.setRelativePostion(Number(value.relx), Number(value.rely), value.margin_target);
            }
            return com;
        };
        D5Component.getComponentByURL = function (res, container, callback) {
            PIXI.Assets.load(res).then(function (uiconf) {
                D5Component.getComponentByJSON(res, uiconf, container);
                callback.apply(container);
            });
        };
        return D5Component;
    }(d5.DisplayContainer));
    d5.D5Component = D5Component;
    __reflect(D5Component.prototype, "d5.D5Component");
})(d5 || (d5 = {}));
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
var d5;
(function (d5) {
    var PI = Math.PI;
    var TwoPI = PI * 2;
    var DEG_TO_RAD = PI / 180;
    var matrixPool = [];
    /**
     * The Matrix class represents a transformation matrix that determines how to map points from one coordinate space to
     * another. You can perform various graphical transformations on a display object by setting the properties of a Matrix
     * object, applying that Matrix object to the matrix property of a display object, These transformation functions include
     * translation (x and y repositioning), rotation, scaling, and skewing.
     * @version Egret 2.4
     * @platform Web,Native
     * @includeExample egret/geom/Matrix.ts
     * @language en_US
     */
    /**
     * Matrix 类表示一个转换矩阵，它确定如何将点从一个坐标空间映射到另一个坐标空间。
     * 您可以对一个显示对象执行不同的图形转换，方法是设置 Matrix 对象的属性，将该 Matrix
     * 对象应用于显示对象的 matrix 属性。这些转换函数包括平移（x 和 y 重新定位）、旋转、缩放和倾斜。
     * @version Egret 2.4
     * @platform Web,Native
     * @includeExample egret/geom/Matrix.ts
     * @language zh_CN
     */
    var Matrix = (function () {
        /**
         * Creates a new Matrix object with the specified parameters.
         * @param a The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
         * @param b The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
         * @param c The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
         * @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image..
         * @param tx The distance by which to translate each point along the x axis.
         * @param ty The distance by which to translate each point along the y axis.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 使用指定参数创建一个 Matrix 对象
         * @param a 缩放或旋转图像时影响像素沿 x 轴定位的值。
         * @param b 旋转或倾斜图像时影响像素沿 y 轴定位的值。
         * @param c 旋转或倾斜图像时影响像素沿 x 轴定位的值。
         * @param d 缩放或旋转图像时影响像素沿 y 轴定位的值。
         * @param tx 沿 x 轴平移每个点的距离。
         * @param ty 沿 y 轴平移每个点的距离。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        function Matrix(a, b, c, d, tx, ty) {
            if (a === void 0) { a = 1; }
            if (b === void 0) { b = 0; }
            if (c === void 0) { c = 0; }
            if (d === void 0) { d = 1; }
            if (tx === void 0) { tx = 0; }
            if (ty === void 0) { ty = 0; }
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.tx = tx;
            this.ty = ty;
        }
        /**
         * Releases a matrix instance to the object pool
         * @param matrix matrix that Needs to be recycled
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 释放一个Matrix实例到对象池
         * @param matrix 需要回收的 matrix
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.release = function (matrix) {
            if (!matrix) {
                return;
            }
            matrixPool.push(matrix);
        };
        /**
         * get a matrix instance from the object pool or create a new one.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 从对象池中取出或创建一个新的Matrix对象。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.create = function () {
            var matrix = matrixPool.pop();
            if (!matrix) {
                matrix = new Matrix();
            }
            return matrix;
        };
        /**
         * Returns a new Matrix object that is a clone of this matrix, with an exact copy of the contained object.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 返回一个新的 Matrix 对象，它是此矩阵的克隆，带有与所含对象完全相同的副本。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.clone = function () {
            return new Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty);
        };
        /**
         * Concatenates a matrix with the current matrix, effectively combining the geometric effects of the two. In mathematical
         * terms, concatenating two matrixes is the same as combining them using matrix multiplication.
         * @param other The matrix to be concatenated to the source matrix.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将某个矩阵与当前矩阵连接，从而将这两个矩阵的几何效果有效地结合在一起。在数学术语中，将两个矩阵连接起来与使用矩阵乘法将它们结合起来是相同的。
         * @param other 要连接到源矩阵的矩阵。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.concat = function (other) {
            var a = this.a * other.a;
            var b = 0.0;
            var c = 0.0;
            var d = this.d * other.d;
            var tx = this.tx * other.a + other.tx;
            var ty = this.ty * other.d + other.ty;
            if (this.b !== 0.0 || this.c !== 0.0 || other.b !== 0.0 || other.c !== 0.0) {
                a += this.b * other.c;
                d += this.c * other.b;
                b += this.a * other.b + this.b * other.d;
                c += this.c * other.a + this.d * other.c;
                tx += this.ty * other.c;
                ty += this.tx * other.b;
            }
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.tx = tx;
            this.ty = ty;
        };
        /**
         * Copies all of the matrix data from the source Point object into the calling Matrix object.
         * @param other  The Matrix object from which to copy the data.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将源 Matrix 对象中的所有矩阵数据复制到调用方 Matrix 对象中。
         * @param other 要拷贝的目标矩阵
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.copyFrom = function (other) {
            this.a = other.a;
            this.b = other.b;
            this.c = other.c;
            this.d = other.d;
            this.tx = other.tx;
            this.ty = other.ty;
            return this;
        };
        /**
         * Sets each matrix property to a value that causes a null transformation. An object transformed by applying an
         * identity matrix will be identical to the original. After calling the identity() method, the resulting matrix
         * has the following properties: a=1, b=0, c=0, d=1, tx=0, ty=0.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 为每个矩阵属性设置一个值，该值将导致矩阵无转换。通过应用恒等矩阵转换的对象将与原始对象完全相同。
         * 调用 identity() 方法后，生成的矩阵具有以下属性：a=1、b=0、c=0、d=1、tx=0 和 ty=0。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.identity = function () {
            this.a = this.d = 1;
            this.b = this.c = this.tx = this.ty = 0;
        };
        /**
         * Performs the opposite transformation of the original matrix. You can apply an inverted matrix to an object to
         * undo the transformation performed when applying the original matrix.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 执行原始矩阵的逆转换。
         * 您可以将一个逆矩阵应用于对象来撤消在应用原始矩阵时执行的转换。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.invert = function () {
            this.$invertInto(this);
        };
        /**
         * @private
         */
        Matrix.prototype.$invertInto = function (target) {
            var a = this.a;
            var b = this.b;
            var c = this.c;
            var d = this.d;
            var tx = this.tx;
            var ty = this.ty;
            if (b == 0 && c == 0) {
                target.b = target.c = 0;
                if (a == 0 || d == 0) {
                    target.a = target.d = target.tx = target.ty = 0;
                }
                else {
                    a = target.a = 1 / a;
                    d = target.d = 1 / d;
                    target.tx = -a * tx;
                    target.ty = -d * ty;
                }
                return;
            }
            var determinant = a * d - b * c;
            if (determinant == 0) {
                target.identity();
                return;
            }
            determinant = 1 / determinant;
            var k = target.a = d * determinant;
            b = target.b = -b * determinant;
            c = target.c = -c * determinant;
            d = target.d = a * determinant;
            target.tx = -(k * tx + c * ty);
            target.ty = -(b * tx + d * ty);
        };
        /**
         * Applies a rotation transformation to the Matrix object.
         * The rotate() method alters the a, b, c, and d properties of the Matrix object.
         * @param angle The rotation angle in radians.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 对 Matrix 对象应用旋转转换。
         * rotate() 方法将更改 Matrix 对象的 a、b、c 和 d 属性。
         * @param angle 以弧度为单位的旋转角度。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.rotate = function (angle) {
            angle = +angle;
            if (angle !== 0) {
                angle = angle / DEG_TO_RAD;
                var u = d5.NumberUtils.cos(angle);
                var v = d5.NumberUtils.sin(angle);
                var ta = this.a;
                var tb = this.b;
                var tc = this.c;
                var td = this.d;
                var ttx = this.tx;
                var tty = this.ty;
                this.a = ta * u - tb * v;
                this.b = ta * v + tb * u;
                this.c = tc * u - td * v;
                this.d = tc * v + td * u;
                this.tx = ttx * u - tty * v;
                this.ty = ttx * v + tty * u;
            }
        };
        /**
         * Applies a scaling transformation to the matrix. The x axis is multiplied by sx, and the y axis it is multiplied by sy.
         * The scale() method alters the a and d properties of the Matrix object.
         * @param sx A multiplier used to scale the object along the x axis.
         * @param sy A multiplier used to scale the object along the y axis.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 对矩阵应用缩放转换。x 轴乘以 sx，y 轴乘以 sy。
         * scale() 方法将更改 Matrix 对象的 a 和 d 属性。
         * @param sx 用于沿 x 轴缩放对象的乘数。
         * @param sy 用于沿 y 轴缩放对象的乘数。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.scale = function (sx, sy) {
            if (sx !== 1) {
                this.a *= sx;
                this.c *= sx;
                this.tx *= sx;
            }
            if (sy !== 1) {
                this.b *= sy;
                this.d *= sy;
                this.ty *= sy;
            }
        };
        /**
         * Sets the members of Matrix to the specified values
         * @param a The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
         * @param b The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
         * @param c The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
         * @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image..
         * @param tx The distance by which to translate each point along the x axis.
         * @param ty The distance by which to translate each point along the y axis.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将 Matrix 的成员设置为指定值
         * @param a 缩放或旋转图像时影响像素沿 x 轴定位的值。
         * @param b 旋转或倾斜图像时影响像素沿 y 轴定位的值。
         * @param c 旋转或倾斜图像时影响像素沿 x 轴定位的值。
         * @param d 缩放或旋转图像时影响像素沿 y 轴定位的值。
         * @param tx 沿 x 轴平移每个点的距离。
         * @param ty 沿 y 轴平移每个点的距离。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.setTo = function (a, b, c, d, tx, ty) {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.tx = tx;
            this.ty = ty;
            return this;
        };
        /**
         * Returns the result of applying the geometric transformation represented by the Matrix object to the specified point.
         * @param pointX The x coordinate for which you want to get the result of the Matrix transformation.
         * @param pointY The y coordinate for which you want to get the result of the Matrix transformation.
         * @param resultPoint A reusable instance of Point for saving the results. Passing this parameter can reduce the
         * number of reallocate objects, which allows you to get better code execution performance.
         * @returns The point resulting from applying the Matrix transformation.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 返回将 Matrix 对象表示的几何转换应用于指定点所产生的结果。
         * @param pointX 想要获得其矩阵转换结果的点的x坐标。
         * @param pointY 想要获得其矩阵转换结果的点的y坐标。
         * @param resultPoint 框架建议尽可能减少创建对象次数来优化性能，可以从外部传入一个复用的Point对象来存储结果，若不传入将创建一个新的Point对象返回。
         * @returns 由应用矩阵转换所产生的点。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.transformPoint = function (pointX, pointY, resultPoint) {
            var x = this.a * pointX + this.c * pointY + this.tx;
            var y = this.b * pointX + this.d * pointY + this.ty;
            if (resultPoint) {
                resultPoint.setTo(x, y);
                return resultPoint;
            }
            return new d5.Point(x, y);
        };
        /**
         * Translates the matrix along the x and y axes, as specified by the dx and dy parameters.
         * @param dx The amount of movement along the x axis to the right, in pixels.
         * @param dy The amount of movement down along the y axis, in pixels.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 沿 x 和 y 轴平移矩阵，由 dx 和 dy 参数指定。
         * @param dx 沿 x 轴向右移动的量（以像素为单位）。
         * @param dy 沿 y 轴向下移动的量（以像素为单位）。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.translate = function (dx, dy) {
            this.tx += dx;
            this.ty += dy;
        };
        /**
         * Determines whether two matrixes are equal.
         * @param other The matrix to be compared.
         * @returns A value of true if the object is equal to this Matrix object; false if it is not equal.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 是否与另一个矩阵数据相等
         * @param other 要比较的另一个矩阵对象。
         * @returns 是否相等，ture表示相等。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.equals = function (other) {
            return this.a == other.a && this.b == other.b &&
                this.c == other.c && this.d == other.d &&
                this.tx == other.tx && this.ty == other.ty;
        };
        /**
         * prepend matrix
         * @param a The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
         * @param b The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
         * @param c The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
         * @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image..
         * @param tx The distance by which to translate each point along the x axis.
         * @param ty The distance by which to translate each point along the y axis.
         * @returns matrix
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 前置矩阵
         * @param a 缩放或旋转图像时影响像素沿 x 轴定位的值
         * @param b 缩放或旋转图像时影响像素沿 y 轴定位的值
         * @param c 缩放或旋转图像时影响像素沿 x 轴定位的值
         * @param d 缩放或旋转图像时影响像素沿 y 轴定位的值
         * @param tx 沿 x 轴平移每个点的距离
         * @param ty 沿 y 轴平移每个点的距离
         * @returns 矩阵自身
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.prepend = function (a, b, c, d, tx, ty) {
            var tx1 = this.tx;
            if (a != 1 || b != 0 || c != 0 || d != 1) {
                var a1 = this.a;
                var c1 = this.c;
                this.a = a1 * a + this.b * c;
                this.b = a1 * b + this.b * d;
                this.c = c1 * a + this.d * c;
                this.d = c1 * b + this.d * d;
            }
            this.tx = tx1 * a + this.ty * c + tx;
            this.ty = tx1 * b + this.ty * d + ty;
            return this;
        };
        /**
         * append matrix
         * @param a The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
         * @param b The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
         * @param c The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
         * @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image..
         * @param tx The distance by which to translate each point along the x axis.
         * @param ty The distance by which to translate each point along the y axis.
         * @returns matrix
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 后置矩阵
         * @param a 缩放或旋转图像时影响像素沿 x 轴定位的值
         * @param b 缩放或旋转图像时影响像素沿 y 轴定位的值
         * @param c 缩放或旋转图像时影响像素沿 x 轴定位的值
         * @param d 缩放或旋转图像时影响像素沿 y 轴定位的值
         * @param tx 沿 x 轴平移每个点的距离
         * @param ty 沿 y 轴平移每个点的距离
         * @returns 矩阵自身
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.append = function (a, b, c, d, tx, ty) {
            var a1 = this.a;
            var b1 = this.b;
            var c1 = this.c;
            var d1 = this.d;
            if (a != 1 || b != 0 || c != 0 || d != 1) {
                this.a = a * a1 + b * c1;
                this.b = a * b1 + b * d1;
                this.c = c * a1 + d * c1;
                this.d = c * b1 + d * d1;
            }
            this.tx = tx * a1 + ty * c1 + this.tx;
            this.ty = tx * b1 + ty * d1 + this.ty;
            return this;
        };
        /**
         * Given a point in the pretransform coordinate space, returns the coordinates of that point after the transformation occurs.
         * Unlike the standard transformation applied using the transformPoint() method, the deltaTransformPoint() method's transformation does not consider the translation parameters tx and ty.
         * @param point The point for which you want to get the result of the matrix transformation.
         * @returns The point resulting from applying the matrix transformation.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 如果给定预转换坐标空间中的点，则此方法返回发生转换后该点的坐标。
         * 与使用 transformPoint() 方法应用的标准转换不同，deltaTransformPoint() 方法的转换不考虑转换参数 tx 和 ty。
         * @param point 想要获得其矩阵转换结果的点
         * @returns 由应用矩阵转换所产生的点
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.deltaTransformPoint = function (point) {
            var self = this;
            var x = self.a * point.x + self.c * point.y;
            var y = self.b * point.x + self.d * point.y;
            return new d5.Point(x, y);
        };
        /**
         * Returns a text value listing the properties of the Matrix object.
         * @returns A string containing the values of the properties of the Matrix object: a, b, c, d, tx, and ty.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 返回将 Matrix 对象表示的几何转换应用于指定点所产生的结果。
         * @returns 一个字符串，它包含 Matrix 对象的属性值：a、b、c、d、tx 和 ty。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.toString = function () {
            return "(a=" + this.a + ", b=" + this.b + ", c=" + this.c + ", d=" + this.d + ", tx=" + this.tx + ", ty=" + this.ty + ")";
        };
        /**
         * Includes parameters for scaling, rotation, and translation. When applied to a matrix it sets the matrix's values based on those parameters.
         * @param scaleX The factor by which to scale horizontally.
         * @param scaleY The factor by which scale vertically.
         * @param rotation The amount to rotate, in radians.
         * @param tx The number of pixels to translate (move) to the right along the x axis.
         * @param ty The number of pixels to translate (move) down along the y axis.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 包括用于缩放、旋转和转换的参数。当应用于矩阵时，该方法会基于这些参数设置矩阵的值。
         * @param scaleX 水平缩放所用的系数
         * @param scaleY 垂直缩放所用的系数
         * @param rotation 旋转量（以弧度为单位）
         * @param tx 沿 x 轴向右平移（移动）的像素数
         * @param ty 沿 y 轴向下平移（移动）的像素数
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.createBox = function (scaleX, scaleY, rotation, tx, ty) {
            if (rotation === void 0) { rotation = 0; }
            if (tx === void 0) { tx = 0; }
            if (ty === void 0) { ty = 0; }
            var self = this;
            if (rotation !== 0) {
                rotation = rotation / DEG_TO_RAD;
                var u = d5.NumberUtils.cos(rotation);
                var v = d5.NumberUtils.sin(rotation);
                self.a = u * scaleX;
                self.b = v * scaleY;
                self.c = -v * scaleX;
                self.d = u * scaleY;
            }
            else {
                self.a = scaleX;
                self.b = 0;
                self.c = 0;
                self.d = scaleY;
            }
            self.tx = tx;
            self.ty = ty;
        };
        /**
         * Creates the specific style of matrix expected by the beginGradientFill() and lineGradientStyle() methods of the Graphics class.
         * Width and height are scaled to a scaleX/scaleY pair and the tx/ty values are offset by half the width and height.
         * @param width The width of the gradient box.
         * @param height The height of the gradient box.
         * @param rotation The amount to rotate, in radians.
         * @param tx The distance, in pixels, to translate to the right along the x axis. This value is offset by half of the width parameter.
         * @param ty The distance, in pixels, to translate down along the y axis. This value is offset by half of the height parameter.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 创建 Graphics 类的 beginGradientFill() 和 lineGradientStyle() 方法所需的矩阵的特定样式。
         * 宽度和高度被缩放为 scaleX/scaleY 对，而 tx/ty 值偏移了宽度和高度的一半。
         * @param width 渐变框的宽度
         * @param height 渐变框的高度
         * @param rotation 旋转量（以弧度为单位）
         * @param tx 沿 x 轴向右平移的距离（以像素为单位）。此值将偏移 width 参数的一半
         * @param ty 沿 y 轴向下平移的距离（以像素为单位）。此值将偏移 height 参数的一半
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Matrix.prototype.createGradientBox = function (width, height, rotation, tx, ty) {
            if (rotation === void 0) { rotation = 0; }
            if (tx === void 0) { tx = 0; }
            if (ty === void 0) { ty = 0; }
            this.createBox(width / 1638.4, height / 1638.4, rotation, tx + width / 2, ty + height / 2);
        };
        /**
         * @private
         */
        Matrix.prototype.$transformBounds = function (bounds) {
            var a = this.a;
            var b = this.b;
            var c = this.c;
            var d = this.d;
            var tx = this.tx;
            var ty = this.ty;
            var x = bounds.x;
            var y = bounds.y;
            var xMax = x + bounds.width;
            var yMax = y + bounds.height;
            var x0 = a * x + c * y + tx;
            var y0 = b * x + d * y + ty;
            var x1 = a * xMax + c * y + tx;
            var y1 = b * xMax + d * y + ty;
            var x2 = a * xMax + c * yMax + tx;
            var y2 = b * xMax + d * yMax + ty;
            var x3 = a * x + c * yMax + tx;
            var y3 = b * x + d * yMax + ty;
            var tmp = 0;
            if (x0 > x1) {
                tmp = x0;
                x0 = x1;
                x1 = tmp;
            }
            if (x2 > x3) {
                tmp = x2;
                x2 = x3;
                x3 = tmp;
            }
            bounds.x = Math.floor(x0 < x2 ? x0 : x2);
            bounds.width = Math.ceil((x1 > x3 ? x1 : x3) - bounds.x);
            if (y0 > y1) {
                tmp = y0;
                y0 = y1;
                y1 = tmp;
            }
            if (y2 > y3) {
                tmp = y2;
                y2 = y3;
                y3 = tmp;
            }
            bounds.y = Math.floor(y0 < y2 ? y0 : y2);
            bounds.height = Math.ceil((y1 > y3 ? y1 : y3) - bounds.y);
        };
        /**
         * @private
         */
        Matrix.prototype.getDeterminant = function () {
            return this.a * this.d - this.b * this.c;
        };
        /**
         * @private
         */
        Matrix.prototype.$getScaleX = function () {
            var m = this;
            if (m.b == 0) {
                return m.a;
            }
            var result = Math.sqrt(m.a * m.a + m.b * m.b);
            return this.getDeterminant() < 0 ? -result : result;
        };
        /**
         * @private
         */
        Matrix.prototype.$getScaleY = function () {
            var m = this;
            if (m.c == 0) {
                return m.d;
            }
            var result = Math.sqrt(m.c * m.c + m.d * m.d);
            return this.getDeterminant() < 0 ? -result : result;
        };
        /**
         * @private
         */
        Matrix.prototype.$getSkewX = function () {
            if (this.d < 0) {
                return Math.atan2(this.d, this.c) + (PI / 2);
            }
            else {
                return Math.atan2(this.d, this.c) - (PI / 2);
            }
        };
        /**
         * @private
         */
        Matrix.prototype.$getSkewY = function () {
            if (this.a < 0) {
                return Math.atan2(this.b, this.a) - PI;
            }
            else {
                return Math.atan2(this.b, this.a);
            }
        };
        /**
         * @private
         */
        Matrix.prototype.$updateScaleAndRotation = function (scaleX, scaleY, skewX, skewY) {
            if ((skewX == 0 || skewX == TwoPI) && (skewY == 0 || skewY == TwoPI)) {
                this.a = scaleX;
                this.b = this.c = 0;
                this.d = scaleY;
                return;
            }
            skewX = skewX / DEG_TO_RAD;
            skewY = skewY / DEG_TO_RAD;
            var u = d5.NumberUtils.cos(skewX);
            var v = d5.NumberUtils.sin(skewX);
            if (skewX == skewY) {
                this.a = u * scaleX;
                this.b = v * scaleX;
            }
            else {
                this.a = d5.NumberUtils.cos(skewY) * scaleX;
                this.b = d5.NumberUtils.sin(skewY) * scaleX;
            }
            this.c = -v * scaleY;
            this.d = u * scaleY;
        };
        /**
         * @private
         * target = other * this
         */
        Matrix.prototype.$preMultiplyInto = function (other, target) {
            var a = other.a * this.a;
            var b = 0.0;
            var c = 0.0;
            var d = other.d * this.d;
            var tx = other.tx * this.a + this.tx;
            var ty = other.ty * this.d + this.ty;
            if (other.b !== 0.0 || other.c !== 0.0 || this.b !== 0.0 || this.c !== 0.0) {
                a += other.b * this.c;
                d += other.c * this.b;
                b += other.a * this.b + other.b * this.d;
                c += other.c * this.a + other.d * this.c;
                tx += other.ty * this.c;
                ty += other.tx * this.b;
            }
            target.a = a;
            target.b = b;
            target.c = c;
            target.d = d;
            target.tx = tx;
            target.ty = ty;
        };
        return Matrix;
    }());
    d5.Matrix = Matrix;
    __reflect(Matrix.prototype, "d5.Matrix");
    /**
     * @private
     * 仅供框架内复用，要防止暴露引用到外部。
     */
    d5.$TempMatrix = new Matrix();
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5HBox = (function (_super) {
        __extends(D5HBox, _super);
        function D5HBox() {
            var _this = _super.call(this) || this;
            _this._padding = 5;
            return _this;
        }
        D5HBox.prototype.addChild = function (child) {
            _super.prototype.addChild.call(this, child);
            this.asyncDraw();
            return child;
        };
        /**
         * Override of removeChild to force layout;
         */
        D5HBox.prototype.removeChild = function (child) {
            _super.prototype.removeChild.call(this, child);
            this.asyncDraw();
            return child;
        };
        D5HBox.prototype.removeChildren = function () {
            _super.prototype.removeChildren.call(this);
            this.asyncDraw();
        };
        /**
         * Draws the visual ui of the component, in this case, laying out the sub components.
         */
        D5HBox.prototype.draw = function () {
            var _w = 0;
            var _h = 0;
            var xpos = 0;
            var i = 0;
            for (i = 0; i < this.numChildren; i++) {
                var child = this.getChildAt(i);
                child.x = xpos;
                xpos += child.d5component ? child.d5component.width : child.width;
                xpos += this._padding;
                _w = xpos;
                _h = Math.max(_h, child.height);
            }
        };
        Object.defineProperty(D5HBox.prototype, "padding", {
            get: function () {
                return this._padding;
            },
            set: function (s) {
                this._padding = s;
                this.asyncDraw();
            },
            enumerable: true,
            configurable: true
        });
        return D5HBox;
    }(d5.D5Component));
    d5.D5HBox = D5HBox;
    __reflect(D5HBox.prototype, "d5.D5HBox");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5UI = (function (_super) {
        __extends(D5UI, _super);
        function D5UI(uiconf, isJson) {
            if (isJson === void 0) { isJson = false; }
            var _this = _super.call(this) || this;
            if (isJson) {
                d5.D5Component.getComponentByJSON("json", JSON.parse(uiconf), _this);
                _this.onReady();
            }
            else {
                d5.D5Component.getComponentByURL(uiconf, _this, _this.onReady);
            }
            return _this;
        }
        /**
         *
         * @param area 允许拖动的顶部高度
         */
        D5UI.prototype.allowDrag = function (area) {
            if (area === void 0) { area = 30; }
            var bg = this._monitor.getChildAt(0).d5component;
            var that = this;
            function onDragMove(event) {
                that._monitor.parent.toLocal(event.global, null, that._monitor.position);
                that._monitor.position.x -= event.local.x;
            }
            function onDragStart(event) {
                if (event.client.y > area)
                    return;
                bg.addEventListener(d5.TouchEvent.TOUCH_MOVE, onDragMove);
            }
            function onDragEnd(event) {
                bg.removeEventListener(d5.TouchEvent.TOUCH_MOVE, onDragMove);
            }
            if (bg) {
                bg.touchEnable = true;
                D5Power.stage.hitArea = D5Power.screen;
                bg.addEventListener(d5.TouchEvent.TOUCH_UP, onDragEnd);
                bg.addEventListener(d5.TouchEvent.TOUCH_MOVEOUT, onDragEnd);
                bg.addEventListener(d5.TouchEvent.TOUCH_BEGIN, onDragStart);
            }
        };
        D5UI.prototype.setFly = function (fx, fy) {
            if (fx === void 0) { fx = NaN; }
            if (fy === void 0) { fy = NaN; }
            if (!isNaN(fx) && !isNaN(fy)) {
                this._flyX = fx;
                this._flyY = fy;
            }
            if (this._flyX == 0 && this._flyY == 0)
                return;
            if (!isNaN(this._flyX) && !isNaN(this._flyY) && this._monitor) {
                this._monitor.x = this._flyX == 1 ? (D5Power.stageWidth - this._realWidth) : Math.ceil(this._flyX == .5 ? (D5Power.stageWidth - this._realWidth) >> 1 : (D5Power.stageWidth * this._flyX));
                this._monitor.y = this._flyY == 1 ? (D5Power.stageHeight - this._realHeight) : Math.ceil(this._flyY == .5 ? (D5Power.stageHeight - this._realHeight) >> 1 : (D5Power.stageHeight * this._flyY));
            }
        };
        D5UI.prototype.setSize = function (w, h) {
            this._realWidth = w;
            this._realHeight = h;
        };
        D5UI.prototype.onReady = function () {
            this._isReady = true;
            this.setFly();
            this.onLoaded();
            this.dispathEvent(d5.Event.COMPLETE, this);
        };
        D5UI.prototype.dispose = function () {
            this._monitor.parent && this._monitor.parent.removeChild(this._monitor);
        };
        D5UI.prototype.onLoaded = function () {
        };
        return D5UI;
    }(d5.DisplayContainer));
    d5.D5UI = D5UI;
    __reflect(D5UI.prototype, "d5.D5UI");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5Loop = (function (_super) {
        __extends(D5Loop, _super);
        function D5Loop() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        D5Loop.prototype.clone = function () {
            var newone = new D5Loop();
            newone.init.apply(newone, this._initArgs);
            newone.setSize(this.width, this.height);
            return newone;
        };
        D5Loop.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            _super.prototype.init.apply(this, args);
            var uiresource = args[0];
            var skinId = args[1];
            var _cut0 = args[2];
            this._mode = args[3];
            this._pin_position = args[4];
            if (!skinId)
                throw new Error("[D5MirrorBox] skinId is not set (" + skinId + ")");
            if (uiresource == null)
                uiresource = d5.D5Component.uiresource;
            if (!uiresource || !uiresource.textures || !uiresource.textures[skinId + '.t']) {
                console.log("Can not find uiresource " + skinId + '.t in ' + uiresource);
                return;
            }
            else {
                this._monitor.addChild(this._front = new PIXI.Sprite(uiresource.textures[skinId + '.lt']));
                this._monitor.addChild(this._ender = new PIXI.Sprite(uiresource.textures[skinId + '.rt']));
                this._monitor.addChild(this._center = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.t'] }));
            }
        };
        D5Loop.prototype.setPin = function (val) {
            this._pin_position = val;
        };
        D5Loop.prototype.setSize = function (w, h) {
            var targetSize;
            if (this._mode == 0) {
                this._center.x = this._front.width;
                targetSize = w - this._front.width * 2;
                targetSize < 0 && (targetSize = 0);
                targetSize > 0 ? (this._center.width = targetSize) : (this._center.visible = false);
                this._ender.x = this._center.x + targetSize;
            }
            else {
                this._center.y = this._front.height;
                targetSize = h - this._front.height * 2;
                targetSize < 0 && (targetSize = 0);
                targetSize > 0 ? (this._center.height = targetSize) : (this._center.visible = false);
                this._ender.y = this._center.y + targetSize;
            }
            _super.prototype.setSize.call(this, w, h);
        };
        return D5Loop;
    }(d5.D5Component));
    d5.D5Loop = D5Loop;
    __reflect(D5Loop.prototype, "d5.D5Loop");
})(d5 || (d5 = {}));
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var d5;
(function (d5) {
    var MD5 = (function () {
        function MD5() {
            this.hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase        */
            this.b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance   */
        }
        /*
        * These are the privates you'll usually want to call
        * They take string arguments and return either hex or base-64 encoded strings
        */
        MD5.prototype.hex_md5 = function (s) { return this.rstr2hex(this.rstr_md5(this.str2rstr_utf8(s))); };
        MD5.prototype.b64_md5 = function (s) { return this.rstr2b64(this.rstr_md5(this.str2rstr_utf8(s))); };
        MD5.prototype.any_md5 = function (s, e) { return this.rstr2any(this.rstr_md5(this.str2rstr_utf8(s)), e); };
        MD5.prototype.hex_hmac_md5 = function (k, d) { return this.rstr2hex(this.rstr_hmac_md5(this.str2rstr_utf8(k), this.str2rstr_utf8(d))); };
        MD5.prototype.b64_hmac_md5 = function (k, d) { return this.rstr2b64(this.rstr_hmac_md5(this.str2rstr_utf8(k), this.str2rstr_utf8(d))); };
        MD5.prototype.any_hmac_md5 = function (k, d, e) { return this.rstr2any(this.rstr_hmac_md5(this.str2rstr_utf8(k), this.str2rstr_utf8(d)), e); };
        /*
        * Perform a simple self-test to see if the VM is working
        */
        MD5.prototype.md5_vm_test = function () {
            return this.hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
        };
        /*
        * Calculate the MD5 of a raw string
        */
        MD5.prototype.rstr_md5 = function (s) {
            return this.binl2rstr(this.binl_md5(this.rstr2binl(s), s.length * 8));
        };
        /*
        * Calculate the HMAC-MD5, of a key and some data (raw strings)
        */
        MD5.prototype.rstr_hmac_md5 = function (key, data) {
            var bkey = this.rstr2binl(key);
            if (bkey.length > 16)
                bkey = this.binl_md5(bkey, key.length * 8);
            var ipad = Array(16), opad = Array(16);
            for (var i = 0; i < 16; i++) {
                ipad[i] = bkey[i] ^ 0x36363636;
                opad[i] = bkey[i] ^ 0x5C5C5C5C;
            }
            var hash = this.binl_md5(ipad.concat(this.rstr2binl(data)), 512 + data.length * 8);
            return this.binl2rstr(this.binl_md5(opad.concat(hash), 512 + 128));
        };
        /*
        * Convert a raw string to a hex string
        */
        MD5.prototype.rstr2hex = function (input) {
            try {
                this.hexcase;
            }
            catch (e) {
                this.hexcase = 0;
            }
            var hex_tab = this.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
            var output = "";
            var x;
            for (var i = 0; i < input.length; i++) {
                x = input.charCodeAt(i);
                output += hex_tab.charAt((x >>> 4) & 0x0F)
                    + hex_tab.charAt(x & 0x0F);
            }
            return output;
        };
        /*
        * Convert a raw string to a base-64 string
        */
        MD5.prototype.rstr2b64 = function (input) {
            try {
                this.b64pad;
            }
            catch (e) {
                this.b64pad = '';
            }
            var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            var output = "";
            var len = input.length;
            for (var i = 0; i < len; i += 3) {
                var triplet = (input.charCodeAt(i) << 16)
                    | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0)
                    | (i + 2 < len ? input.charCodeAt(i + 2) : 0);
                for (var j = 0; j < 4; j++) {
                    if (i * 8 + j * 6 > input.length * 8)
                        output += this.b64pad;
                    else
                        output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F);
                }
            }
            return output;
        };
        /*
        * Convert a raw string to an arbitrary string encoding
        */
        MD5.prototype.rstr2any = function (input, encoding) {
            var divisor = encoding.length;
            var i, j, q, x, quotient;
            /* Convert to an array of 16-bit big-endian values, forming the dividend */
            var dividend = Array(Math.ceil(input.length / 2));
            for (i = 0; i < dividend.length; i++) {
                dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
            }
            /*
            * Repeatedly perform a long division. The binary array forms the dividend,
            * the length of the encoding is the divisor. Once computed, the quotient
            * forms the dividend for the next step. All remainders are stored for later
            * use.
            */
            var full_length = Math.ceil(input.length * 8 /
                (Math.log(encoding.length) / Math.log(2)));
            var remainders = Array(full_length);
            for (j = 0; j < full_length; j++) {
                quotient = Array();
                x = 0;
                for (i = 0; i < dividend.length; i++) {
                    x = (x << 16) + dividend[i];
                    q = Math.floor(x / divisor);
                    x -= q * divisor;
                    if (quotient.length > 0 || q > 0)
                        quotient[quotient.length] = q;
                }
                remainders[j] = x;
                dividend = quotient;
            }
            /* Convert the remainders to the output string */
            var output = "";
            for (i = remainders.length - 1; i >= 0; i--)
                output += encoding.charAt(remainders[i]);
            return output;
        };
        /*
        * Encode a string as utf-8.
        * For efficiency, this assumes the input is valid utf-16.
        */
        MD5.prototype.str2rstr_utf8 = function (input) {
            var output = "";
            var i = -1;
            var x, y;
            while (++i < input.length) {
                /* Decode utf-16 surrogate pairs */
                x = input.charCodeAt(i);
                y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
                if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) {
                    x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
                    i++;
                }
                /* Encode output as utf-8 */
                if (x <= 0x7F)
                    output += String.fromCharCode(x);
                else if (x <= 0x7FF)
                    output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), 0x80 | (x & 0x3F));
                else if (x <= 0xFFFF)
                    output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), 0x80 | ((x >>> 6) & 0x3F), 0x80 | (x & 0x3F));
                else if (x <= 0x1FFFFF)
                    output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3F), 0x80 | ((x >>> 6) & 0x3F), 0x80 | (x & 0x3F));
            }
            return output;
        };
        /*
        * Encode a string as utf-16
        */
        MD5.prototype.str2rstr_utf16le = function (input) {
            var output = "";
            for (var i = 0; i < input.length; i++)
                output += String.fromCharCode(input.charCodeAt(i) & 0xFF, (input.charCodeAt(i) >>> 8) & 0xFF);
            return output;
        };
        MD5.prototype.str2rstr_utf16be = function (input) {
            var output = "";
            for (var i = 0; i < input.length; i++)
                output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF, input.charCodeAt(i) & 0xFF);
            return output;
        };
        /*
        * Convert a raw string to an array of little-endian words
        * Characters >255 have their high-byte silently ignored.
        */
        MD5.prototype.rstr2binl = function (input) {
            var output = Array(input.length >> 2);
            for (var i = 0; i < output.length; i++)
                output[i] = 0;
            for (var i = 0; i < input.length * 8; i += 8)
                output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
            return output;
        };
        /*
        * Convert an array of little-endian words to a string
        */
        MD5.prototype.binl2rstr = function (input) {
            var output = "";
            for (var i = 0; i < input.length * 32; i += 8)
                output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
            return output;
        };
        /*
        * Calculate the MD5 of an array of little-endian words, and a bit length.
        */
        MD5.prototype.binl_md5 = function (x, len) {
            /* append padding */
            x[len >> 5] |= 0x80 << ((len) % 32);
            x[(((len + 64) >>> 9) << 4) + 14] = len;
            var a = 1732584193;
            var b = -271733879;
            var c = -1732584194;
            var d = 271733878;
            for (var i = 0; i < x.length; i += 16) {
                var olda = a;
                var oldb = b;
                var oldc = c;
                var oldd = d;
                a = this.md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
                d = this.md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
                c = this.md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
                b = this.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
                a = this.md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
                d = this.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
                c = this.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
                b = this.md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
                a = this.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
                d = this.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
                c = this.md5_ff(c, d, a, b, x[i + 10], 17, -42063);
                b = this.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
                a = this.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
                d = this.md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
                c = this.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
                b = this.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
                a = this.md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
                d = this.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
                c = this.md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
                b = this.md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
                a = this.md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
                d = this.md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
                c = this.md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
                b = this.md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
                a = this.md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
                d = this.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
                c = this.md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
                b = this.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
                a = this.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
                d = this.md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
                c = this.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
                b = this.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
                a = this.md5_hh(a, b, c, d, x[i + 5], 4, -378558);
                d = this.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
                c = this.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
                b = this.md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
                a = this.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
                d = this.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
                c = this.md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
                b = this.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
                a = this.md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
                d = this.md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
                c = this.md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
                b = this.md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
                a = this.md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
                d = this.md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
                c = this.md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
                b = this.md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
                a = this.md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
                d = this.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
                c = this.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
                b = this.md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
                a = this.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
                d = this.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
                c = this.md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
                b = this.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
                a = this.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
                d = this.md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
                c = this.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
                b = this.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
                a = this.md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
                d = this.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
                c = this.md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
                b = this.md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
                a = this.safe_add(a, olda);
                b = this.safe_add(b, oldb);
                c = this.safe_add(c, oldc);
                d = this.safe_add(d, oldd);
            }
            return [a, b, c, d];
        };
        /*
        * These privates implement the four basic operations the algorithm uses.
        */
        MD5.prototype.md5_cmn = function (q, a, b, x, s, t) {
            return this.safe_add(this.bit_rol(this.safe_add(this.safe_add(a, q), this.safe_add(x, t)), s), b);
        };
        MD5.prototype.md5_ff = function (a, b, c, d, x, s, t) {
            return this.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
        };
        MD5.prototype.md5_gg = function (a, b, c, d, x, s, t) {
            return this.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
        };
        MD5.prototype.md5_hh = function (a, b, c, d, x, s, t) {
            return this.md5_cmn(b ^ c ^ d, a, b, x, s, t);
        };
        MD5.prototype.md5_ii = function (a, b, c, d, x, s, t) {
            return this.md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
        };
        /*
        * Add integers, wrapping at 2^32. This uses 16-bit operations internally
        * to work around bugs in some JS interpreters.
        */
        MD5.prototype.safe_add = function (x, y) {
            var lsw = (x & 0xFFFF) + (y & 0xFFFF);
            var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
            return (msw << 16) | (lsw & 0xFFFF);
        };
        /*
        * Bitwise rotate a 32-bit number to the left.
        */
        MD5.prototype.bit_rol = function (num, cnt) {
            return (num << cnt) | (num >>> (32 - cnt));
        };
        return MD5;
    }());
    d5.MD5 = MD5;
    __reflect(MD5.prototype, "d5.MD5");
})(d5 || (d5 = {}));
/**
 * D5Power游戏框架模版
 *
 * @author D5-Howard(d5@microgame.cn)
 *
 */
var D5Power = (function () {
    function D5Power(app) {
        D5Power._app = app;
        D5Power._start = performance.now();
    }
    Object.defineProperty(D5Power, "uiversion", {
        /**
         * 设置UI素材版本号
         */
        set: function (v) {
            this._uiversion = v;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(D5Power, "md5", {
        get: function () {
            if (!this._md5)
                this._md5 = new d5.MD5();
            return this._md5;
        },
        enumerable: true,
        configurable: true
    });
    D5Power.prototype.initUI = function (path, uiroot) {
        var _this = this;
        if (path === void 0) { path = "uiresource.json"; }
        if (uiroot === void 0) { uiroot = "resource/assets/ui/default/"; }
        var that = this;
        return new Promise(function (resolv, reject) {
            var ui_json;
            var ui_bitmap;
            PIXI.Assets.load(uiroot + "uiresource.json?ver=" + D5Power._uiversion).then(function (res) {
                ui_json = res;
                PIXI.Assets.load(uiroot + "uiresource.png?ver=" + D5Power._uiversion).then(function (bitmap) { return __awaiter(_this, void 0, void 0, function () {
                    var atlasData, key, origin_data, cut, frame, w, perw, frames_1, i, uiresource;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                ui_bitmap = bitmap;
                                atlasData = { frames: {}, meta: { scale: 1 } };
                                for (key in res) {
                                    origin_data = res[key];
                                    cut = origin_data.cut;
                                    frame = void 0;
                                    switch (origin_data.type) {
                                        case "D5Button":
                                        case "D5RadioBtn":
                                            w = origin_data.w;
                                            perw = w / 4;
                                            frames_1 = ['.default', '.over', '.tap', '.disable'];
                                            for (i = 0; i < 4; i++) {
                                                frame = {
                                                    frame: { x: origin_data.x + perw * i, y: origin_data.y, w: perw, h: origin_data.h },
                                                    sourceSize: { w: perw, h: origin_data.h },
                                                    spriteSourceSize: { x: 0, y: 0, w: perw, h: origin_data.h }
                                                };
                                                atlasData.frames[key + frames_1[i]] = frame;
                                            }
                                            break;
                                        case "D5MirrorBox":
                                            frame = {
                                                frame: { x: origin_data.x, y: origin_data.y, w: cut[0].x, h: cut[0].y },
                                                sourceSize: { w: cut[0].x, h: cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[0].x, h: cut[0].y }
                                            };
                                            atlasData.frames[key + ".lt"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[0].x, y: origin_data.y, w: origin_data.w - cut[0].x, h: cut[0].y },
                                                sourceSize: { w: origin_data.w - cut[0].x, h: cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: origin_data.w - cut[0].x, h: cut[0].y }
                                            };
                                            atlasData.frames[key + ".rt"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x, y: origin_data.y + cut[0].y, w: cut[0].x, h: origin_data.h - cut[0].y },
                                                sourceSize: { w: cut[0].x, h: origin_data.h - cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[0].x, h: origin_data.h - cut[0].y }
                                            };
                                            atlasData.frames[key + ".lb"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[0].x, y: origin_data.y + cut[0].y, w: origin_data.w - cut[0].x, h: origin_data.h - cut[0].y },
                                                sourceSize: { w: origin_data.w - cut[0].x, h: origin_data.h - cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: origin_data.w - cut[0].x, h: origin_data.h - cut[0].y }
                                            };
                                            atlasData.frames[key + ".rb"] = frame;
                                            break;
                                        case "D5Window":
                                            frame = {
                                                frame: { x: origin_data.x, y: origin_data.y, w: cut[0].x, h: cut[0].y },
                                                sourceSize: { w: cut[0].x, h: cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[0].x, h: cut[0].y }
                                            };
                                            atlasData.frames[key + ".lt"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[0].x, y: origin_data.y, w: cut[1].x - cut[0].x, h: cut[0].y },
                                                sourceSize: { w: cut[1].x - cut[0].x, h: cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[1].x - cut[0].x, h: cut[0].y }
                                            };
                                            atlasData.frames[key + ".t"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[1].x, y: origin_data.y, w: origin_data.w - cut[1].x, h: cut[0].y },
                                                sourceSize: { w: origin_data.w - cut[1].x, h: cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: origin_data.w - cut[1].x, h: cut[0].y }
                                            };
                                            atlasData.frames[key + ".rt"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x, y: origin_data.y + cut[0].y, w: cut[0].x, h: cut[1].y - cut[0].y },
                                                sourceSize: { w: cut[0].x, h: cut[1].y - cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[0].x, h: cut[1].y - cut[0].y }
                                            };
                                            atlasData.frames[key + ".l"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[0].x, y: origin_data.y + cut[0].y, w: cut[1].x - cut[0].x, h: cut[1].y - cut[0].y },
                                                sourceSize: { w: cut[1].x - cut[0].x, h: cut[1].y - cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[1].x - cut[0].x, h: cut[1].y - cut[0].y }
                                            };
                                            atlasData.frames[key + ".m"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[1].x, y: origin_data.y + cut[0].y, w: origin_data.w - cut[1].x, h: cut[1].y - cut[0].y },
                                                sourceSize: { w: origin_data.w - cut[1].x, h: cut[1].y - cut[0].y },
                                                spriteSourceSize: { x: 0, y: 0, w: origin_data.w - cut[1].x, h: cut[1].y - cut[0].y }
                                            };
                                            atlasData.frames[key + ".r"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x, y: origin_data.y + cut[1].y, w: cut[0].x, h: origin_data.h - cut[1].y },
                                                sourceSize: { w: cut[0].x, h: origin_data.h - cut[1].y },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[0].x, h: origin_data.h - cut[1].y }
                                            };
                                            atlasData.frames[key + ".lb"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[0].x, y: origin_data.y + cut[1].y, w: cut[1].x - cut[0].x, h: origin_data.h - cut[1].y },
                                                sourceSize: { w: cut[1].x - cut[0].x, h: origin_data.h - cut[1].y },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[1].x - cut[0].x, h: origin_data.h - cut[1].y }
                                            };
                                            atlasData.frames[key + ".b"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[1].x, y: origin_data.y + cut[1].y, w: origin_data.w - cut[1].x, h: origin_data.h - cut[1].y },
                                                sourceSize: { w: origin_data.w - cut[1].x, h: origin_data.h - cut[1].y },
                                                spriteSourceSize: { x: 0, y: 0, w: origin_data.w - cut[1].x, h: origin_data.h - cut[1].y }
                                            };
                                            atlasData.frames[key + ".rb"] = frame;
                                            break;
                                        case "D5Loop":
                                            frame = {
                                                frame: { x: origin_data.x, y: origin_data.y, w: cut[0].x, h: origin_data.h },
                                                sourceSize: { w: cut[0].x, h: origin_data.h },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[0].x, h: origin_data.h }
                                            };
                                            atlasData.frames[key + ".lt"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[0].x, y: origin_data.y, w: cut[1].x - cut[0].x, h: origin_data.h },
                                                sourceSize: { w: cut[1].x - cut[0].x, h: origin_data.h },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[1].x - cut[0].x, h: origin_data.h }
                                            };
                                            atlasData.frames[key + ".t"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[1].x, y: origin_data.y, w: origin_data.w - cut[1].x, h: origin_data.h },
                                                sourceSize: { w: origin_data.w - cut[1].x, h: origin_data.h },
                                                spriteSourceSize: { x: 0, y: 0, w: origin_data.w - cut[1].x, h: origin_data.h }
                                            };
                                            atlasData.frames[key + ".rt"] = frame;
                                            break;
                                        case "D5MirrorLoop":
                                            frame = {
                                                frame: { x: origin_data.x, y: origin_data.y, w: cut[0].x, h: origin_data.h },
                                                sourceSize: { w: cut[0].x, h: origin_data.h },
                                                spriteSourceSize: { x: 0, y: 0, w: cut[0].x, h: origin_data.h }
                                            };
                                            atlasData.frames[key + ".l"] = frame;
                                            frame = {
                                                frame: { x: origin_data.x + cut[0].x, y: origin_data.y, w: origin_data.w - cut[0].x, h: origin_data.h },
                                                sourceSize: { w: origin_data.w - cut[0].x, h: origin_data.h },
                                                spriteSourceSize: { x: 0, y: 0, w: origin_data.w - cut[0].x, h: origin_data.h }
                                            };
                                            atlasData.frames[key + ".r"] = frame;
                                            break;
                                        default:
                                            frame = {
                                                frame: { x: origin_data.x, y: origin_data.y, w: origin_data.w, h: origin_data.h },
                                                sourceSize: { w: origin_data.w, h: origin_data.h },
                                                spriteSourceSize: { x: 0, y: 0, w: origin_data.w, h: origin_data.h }
                                            };
                                            atlasData.frames[key] = frame;
                                            break;
                                    }
                                }
                                uiresource = new PIXI.Spritesheet(bitmap, atlasData);
                                return [4 /*yield*/, uiresource.parse()];
                            case 1:
                                _a.sent();
                                that.uiresource = uiresource;
                                resolv(that);
                                return [2 /*return*/];
                        }
                    });
                }); });
            });
        });
    };
    D5Power.getTimer = function () {
        return performance.now() - this._start;
    };
    D5Power.addEnterframe = function (fun) {
        this._app.ticker.add(fun);
    };
    D5Power.removeEnterframe = function (fun) {
        this._app.ticker.remove(fun);
    };
    D5Power.onceEnterframe = function (fun) {
        this._app.ticker.addOnce(fun);
    };
    Object.defineProperty(D5Power, "screen", {
        get: function () {
            return this._app.screen;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(D5Power, "renderer", {
        get: function () {
            return this._app.renderer;
        },
        enumerable: true,
        configurable: true
    });
    D5Power.showFPS = function () {
        var fpsText = new PIXI.Text("FPS: 0", {
            fill: 0xffffff,
            fontSize: 16,
            fontWeight: "bold",
        });
        fpsText.position.set(D5Power.stageWidth - fpsText.width - 20, D5Power.stageHeight - fpsText.height - 20);
        this._app.stage.addChild(fpsText);
        // FPS 计算逻辑
        var lastTime = performance.now();
        var frameCount = 0;
        this._app.ticker.add(function () {
            frameCount++;
            var now = performance.now();
            var delta = now - lastTime;
            // 每 1 秒更新一次 FPS
            if (delta >= 1000) {
                var fps = Math.round((frameCount * 1000) / delta);
                fpsText.text = "FPS: " + fps;
                frameCount = 0;
                lastTime = now;
            }
        });
    };
    D5Power.stageOnce = function (event, listener) {
        var _this = this;
        this._app.stage.eventMode = 'static';
        this._app.stage.once(event, function (e) {
            _this._app.stage.eventMode = 'auto';
            listener.apply(null, [e]);
        });
    };
    D5Power.stageOn = function (event, listener) {
        this._app.stage.eventMode = 'static';
        this._app.stage.on(event, listener);
    };
    D5Power.stageOff = function (event, listener) {
        if (listener === void 0) { listener = null; }
        listener ? this._app.stage.off(event, listener) : this._app.stage.off(event);
    };
    D5Power.setStageSize = function (sw, sh) {
        this._stageW = sw;
        this._stageH = sh;
    };
    Object.defineProperty(D5Power, "stageWidth", {
        get: function () {
            return this._stageW;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(D5Power, "stageHeight", {
        get: function () {
            return this._stageH;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(D5Power, "stage", {
        get: function () {
            return this._app.stage;
        },
        enumerable: true,
        configurable: true
    });
    D5Power.addChild = function (child) {
        this._app.stage.addChild(child.monitor ? child.monitor : child);
    };
    D5Power.removeChild = function (child) {
        this._app.stage.removeChild(child.monitor ? child.monitor : child);
    };
    Object.defineProperty(D5Power.prototype, "uiresource", {
        set: function (res) {
            d5.D5Component.uiresource = res;
        },
        enumerable: true,
        configurable: true
    });
    return D5Power;
}());
__reflect(D5Power.prototype, "D5Power");
var trace = function () {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var input = "";
    for (var i = 0, j = args.length; i < j; i++)
        input += args[i] + ",";
    input = input.substring(0, input.length - 1);
    console.log(input);
};
var d5;
(function (d5) {
    var Config;
    (function (Config) {
        Config["EXTLIB_SPINE"] = "libs/spine-pixi-v8.min.js";
        Config["EXTLIB_DRAGON"] = "libs/dragonbone.min.js";
    })(Config = d5.Config || (d5.Config = {}));
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var Event;
    (function (Event) {
        Event["DISPOSE"] = "dispose";
        Event["REMOVE_FROM_STAGE"] = "dispose";
        Event["SELECT"] = "select";
        Event["COMPLETE"] = "complete";
        Event["CHANGE"] = "change";
        Event["OPENUI"] = "openui";
        Event["UPDATE_COIN"] = "update_coin";
    })(Event = d5.Event || (d5.Event = {}));
    var TouchEvent;
    (function (TouchEvent) {
        TouchEvent["TOUCH_TAP"] = "pointerup";
        TouchEvent["TOUCH_OVER"] = "pointerover";
        TouchEvent["TOUCH_BEGIN"] = "pointerdown";
        TouchEvent["TOUCH_UP"] = "pointerup";
        TouchEvent["TOUCH_MOVEOUT"] = "pointerupoutside";
        TouchEvent["TOUCH_OUT"] = "pointerout";
        TouchEvent["TOUCH_MOVE"] = "pointermove";
        TouchEvent["CURSOR_POINTER"] = "pointer";
    })(TouchEvent = d5.TouchEvent || (d5.TouchEvent = {}));
})(d5 || (d5 = {}));
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
var d5;
(function (d5) {
    /**
     * @version Egret 2.4
     * @platform Web,Native
     */
    var NumberUtils = (function () {
        function NumberUtils() {
        }
        /**
         * Judge whether it is a numerical value
         * @param value Parameter that needs to be judged
         * @returns
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 判断是否是数值
         * @param value 需要判断的参数
         * @returns
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        NumberUtils.isNumber = function (value) {
            return typeof (value) === "number" && !isNaN(value);
        };
        /**
         * Obtain the approximate sin value of the corresponding angle value
         * @param value {number} Angle value
         * @returns {number} sin value
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 得到对应角度值的sin近似值
         * @param value {number} 角度值
         * @returns {number} sin值
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        NumberUtils.sin = function (value) {
            var valueFloor = Math.floor(value);
            var valueCeil = valueFloor + 1;
            var resultFloor = NumberUtils.sinInt(valueFloor);
            if (valueFloor == value) {
                return resultFloor;
            }
            var resultCeil = NumberUtils.sinInt(valueCeil);
            return (value - valueFloor) * resultCeil + (valueCeil - value) * resultFloor;
        };
        /**
         * @private
         *
         * @param value
         * @returns
         */
        NumberUtils.sinInt = function (value) {
            value = value % 360;
            if (value < 0) {
                value += 360;
            }
            return egret_sin_map[value];
        };
        /**
         * Obtain the approximate cos value of the corresponding angle value
         * @param value {number} Angle value
         * @returns {number} cos value
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 得到对应角度值的cos近似值
         * @param value {number} 角度值
         * @returns {number} cos值
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        NumberUtils.cos = function (value) {
            var valueFloor = Math.floor(value);
            var valueCeil = valueFloor + 1;
            var resultFloor = NumberUtils.cosInt(valueFloor);
            if (valueFloor == value) {
                return resultFloor;
            }
            var resultCeil = NumberUtils.cosInt(valueCeil);
            return (value - valueFloor) * resultCeil + (valueCeil - value) * resultFloor;
        };
        /**
         * @private
         *
         * @param value
         * @returns
         */
        NumberUtils.cosInt = function (value) {
            value = value % 360;
            if (value < 0) {
                value += 360;
            }
            return egret_cos_map[value];
        };
        NumberUtils.convertStringToHashCode = function (str) {
            if (str.length === 0) {
                return 0;
            }
            var hash = 0;
            for (var i = 0, length_1 = str.length; i < length_1; ++i) {
                var chr = str.charCodeAt(i);
                hash = ((hash << 5) - hash) + chr;
                hash |= 0; // Convert to 32bit integer
            }
            return hash;
        };
        return NumberUtils;
    }());
    d5.NumberUtils = NumberUtils;
    __reflect(NumberUtils.prototype, "d5.NumberUtils");
})(d5 || (d5 = {}));
/**
 * @private
 */
var egret_sin_map = {};
/**
 * @private
 */
var egret_cos_map = {};
/**
 * @private
 */
var DEG_TO_RAD = Math.PI / 180;
for (var NumberUtils_i = 0; NumberUtils_i < 360; NumberUtils_i++) {
    egret_sin_map[NumberUtils_i] = Math.sin(NumberUtils_i * DEG_TO_RAD);
    egret_cos_map[NumberUtils_i] = Math.cos(NumberUtils_i * DEG_TO_RAD);
}
egret_sin_map[90] = 1;
egret_cos_map[90] = 0;
egret_sin_map[180] = 0;
egret_cos_map[180] = -1;
egret_sin_map[270] = -1;
egret_cos_map[270] = 0;
//对未提供bind的浏览器实现bind机制
if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
        if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5 internal IsCallable function
            trace("[NumberUtils] closest thing possible to the ECMAScript 5 internal IsCallable function");
        }
        var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {
        }, fBound = function () {
            return fToBind.apply(this instanceof fNOP && oThis
                ? this
                : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
        };
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
        return fBound;
    };
}
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
var d5;
(function (d5) {
    var pointPool = [];
    var DEG_TO_RAD = Math.PI / 180;
    /**
     * The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal
     * axis and y represents the vertical axis.
     * @version Egret 2.4
     * @platform Web,Native
     * @includeExample egret/geom/Point.ts
     * @language en_US
     */
    /**
     * Point 对象表示二维坐标系统中的某个位置，其中 x 表示水平轴，y 表示垂直轴。
     * @version Egret 2.4
     * @platform Web,Native
     * @includeExample egret/geom/Point.ts
     * @language zh_CN
     */
    var Point = (function () {
        /**
         * Creates a new point. If you pass no parameters to this method, a point is created at (0,0).
         * @param x The horizontal coordinate.
         * @param y The vertical coordinate.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 创建一个 egret.Point 对象.若不传入任何参数，将会创建一个位于（0，0）位置的点。
         * @param x 该对象的x属性值，默认为0
         * @param y 该对象的y属性值，默认为0
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        function Point(x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            this.x = x;
            this.y = y;
        }
        /**
         * Releases a point instance to the object pool
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 释放一个Point实例到对象池
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.release = function (point) {
            if (!point) {
                return;
            }
            pointPool.push(point);
        };
        /**
         * get a point instance from the object pool or create a new one.
         * @param x The horizontal coordinate.
         * @param y The vertical coordinate.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 从对象池中取出或创建一个新的Point对象。
         * @param x 该对象的x属性值，默认为0
         * @param y 该对象的y属性值，默认为0
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.create = function (x, y) {
            var point = pointPool.pop();
            if (!point) {
                point = new Point();
            }
            return point.setTo(x, y);
        };
        Object.defineProperty(Point.prototype, "length", {
            /**
             * The length of the line segment from (0,0) to this point.
             * @version Egret 2.4
             * @platform Web,Native
             * @language en_US
             */
            /**
             * 从 (0,0) 到此点的线段长度。
             * @version Egret 2.4
             * @platform Web,Native
             * @language zh_CN
             */
            get: function () {
                return Math.sqrt(this.x * this.x + this.y * this.y);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Sets the members of Point to the specified values
         * @param x The horizontal coordinate.
         * @param y The vertical coordinate.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将 Point 的成员设置为指定值
         * @param x 该对象的x属性值
         * @param y 该对象的y属性值
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.setTo = function (x, y) {
            this.x = x;
            this.y = y;
            return this;
        };
        /**
         * Creates a copy of this Point object.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 克隆点对象
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.clone = function () {
            return new Point(this.x, this.y);
        };
        /**
         * Determines whether two points are equal. Two points are equal if they have the same x and y values.
         * @param toCompare The point to be compared.
         * @returns A value of true if the object is equal to this Point object; false if it is not equal.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 确定两个点是否相同。如果两个点具有相同的 x 和 y 值，则它们是相同的点。
         * @param toCompare 要比较的点。
         * @returns 如果该对象与此 Point 对象相同，则为 true 值，如果不相同，则为 false。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.equals = function (toCompare) {
            return this.x == toCompare.x && this.y == toCompare.y;
        };
        /**
         * Returns the distance between pt1 and pt2.
         * @param p1 The first point.
         * @param p2 The second point.
         * @returns The distance between the first and second points.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 返回 pt1 和 pt2 之间的距离。
         * @param p1 第一个点
         * @param p2 第二个点
         * @returns 第一个点和第二个点之间的距离。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.distance = function (p1, p2) {
            return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
        };
        /**
         * Copies all of the point data from the source Point object into the calling Point object.
         * @param sourcePoint The Point object from which to copy the data.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将源 Point 对象中的所有点数据复制到调用方 Point 对象中。
         * @param sourcePoint 要从中复制数据的 Point 对象。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.copyFrom = function (sourcePoint) {
            this.x = sourcePoint.x;
            this.y = sourcePoint.y;
        };
        /**
         * Adds the coordinates of another point to the coordinates of this point to create a new point.
         * @param v The point to be added.
         * @returns The new point.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将另一个点的坐标添加到此点的坐标以创建一个新点。
         * @param v 要添加的点。
         * @returns 新点。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.add = function (v) {
            return new Point(this.x + v.x, this.y + v.y);
        };
        /**
         * Determines a point between two specified points.
         * The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2. The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2).
         * @param pt1 The first point.
         * @param pt2 The second point.
         * @param f The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned.
         * @returns The new interpolated point.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 确定两个指定点之间的点。
         * 参数 f 确定新的内插点相对于参数 pt1 和 pt2 指定的两个端点所处的位置。参数 f 的值越接近 1.0，则内插点就越接近第一个点（参数 pt1）。参数 f 的值越接近 0，则内插点就越接近第二个点（参数 pt2）。
         * @param pt1 第一个点。
         * @param pt2 第二个点。
         * @param f 两个点之间的内插级别。表示新点将位于 pt1 和 pt2 连成的直线上的什么位置。如果 f=1，则返回 pt1；如果 f=0，则返回 pt2。
         * @returns 新的内插点。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.interpolate = function (pt1, pt2, f) {
            var f1 = 1 - f;
            return new Point(pt1.x * f + pt2.x * f1, pt1.y * f + pt2.y * f1);
        };
        /**
         * Scales the line segment between (0,0) and the current point to a set length.
         * @param thickness The scaling value. For example, if the current point is (0,5), and you normalize it to 1, the point returned is at (0,1).
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将 (0,0) 和当前点之间的线段缩放为设定的长度。
         * @param thickness 缩放值。例如，如果当前点为 (0,5) 并且您将它规范化为 1，则返回的点位于 (0,1) 处。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.normalize = function (thickness) {
            if (this.x != 0 || this.y != 0) {
                var relativeThickness = thickness / this.length;
                this.x *= relativeThickness;
                this.y *= relativeThickness;
            }
        };
        /**
         * Offsets the Point object by the specified amount. The value of dx is added to the original value of x to create the new x value. The value of dy is added to the original value of y to create the new y value.
         * @param dx The amount by which to offset the horizontal coordinate, x.
         * @param dy The amount by which to offset the vertical coordinate, y.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 按指定量偏移 Point 对象。dx 的值将添加到 x 的原始值中以创建新的 x 值。dy 的值将添加到 y 的原始值中以创建新的 y 值。
         * @param dx 水平坐标 x 的偏移量。
         * @param dy 水平坐标 y 的偏移量。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.offset = function (dx, dy) {
            this.x += dx;
            this.y += dy;
        };
        /**
         * Converts a pair of polar coordinates to a Cartesian point coordinate.
         * @param len The length coordinate of the polar pair.
         * @param angle The angle, in radians, of the polar pair.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将一对极坐标转换为笛卡尔点坐标。
         * @param len 极坐标对的长度。
         * @param angle 极坐标对的角度（以弧度表示）。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.polar = function (len, angle) {
            return new Point(len * d5.NumberUtils.cos(angle / DEG_TO_RAD), len * d5.NumberUtils.sin(angle / DEG_TO_RAD));
        };
        /**
         * Subtracts the coordinates of another point from the coordinates of this point to create a new point.
         * @param v The point to be subtracted.
         * @returns The new point.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 从此点的坐标中减去另一个点的坐标以创建一个新点。
         * @param v 要减去的点。
         * @returns 新点。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.subtract = function (v) {
            return new Point(this.x - v.x, this.y - v.y);
        };
        /**
         * Returns a string that contains the values of the x and y coordinates. The string has the form "(x=x, y=y)", so calling the toString() method for a point at 23,17 would return "(x=23, y=17)".
         * @returns The string representation of the coordinates.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 返回包含 x 和 y 坐标的值的字符串。该字符串的格式为 "(x=x, y=y)"，因此为点 23,17 调用 toString() 方法将返回 "(x=23, y=17)"。
         * @returns 坐标的字符串表示形式。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Point.prototype.toString = function () {
            return "(x=" + this.x + ", y=" + this.y + ")";
        };
        return Point;
    }());
    d5.Point = Point;
    __reflect(Point.prototype, "d5.Point");
    /**
     * @private
     * 仅供框架内复用，要防止暴露引用到外部。
     */
    d5.$TempPoint = new Point();
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var Point3D = (function () {
        function Point3D(x, y, z) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (z === void 0) { z = 0; }
            this.x = x;
            this.y = y;
            this.z = z;
        }
        Point3D.prototype.toString = function () {
            return "(x=" + this.x + ", y=" + this.y + ", z=" + this.z + ")";
        };
        return Point3D;
    }());
    d5.Point3D = Point3D;
    __reflect(Point3D.prototype, "d5.Point3D");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5Shape = (function (_super) {
        __extends(D5Shape, _super);
        function D5Shape(autoInit) {
            if (autoInit === void 0) { autoInit = true; }
            var _this = _super.call(this) || this;
            _this._workMode = 0;
            _this._tickNess = 0;
            _this._color = -1;
            _this._offX = 0;
            _this._offY = 0;
            _this._radius = 0;
            _this._maskName = '';
            _this.drawAlpha = 1;
            _this.lineAlpha = 1;
            _this._round_0 = 0;
            _this._round_1 = 0;
            _this._round_2 = 0;
            _this._round_3 = 0;
            _this._graphics = new PIXI.Graphics();
            _this._monitor.addChild(_this._graphics);
            return _this;
        }
        D5Shape.prototype.mask = function (v) {
            this._graphics.mask = v._graphics;
        };
        Object.defineProperty(D5Shape.prototype, "graphics", {
            get: function () {
                return this._graphics;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5Shape.prototype, "maskName", {
            set: function (value) {
                if (value == "" || !value)
                    return;
                this._maskName = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5Shape.prototype, "pointString", {
            set: function (value) {
                if (value == "")
                    return;
                var arr = value.split(',');
                this._points = arr;
                /*
                for(let i=0,j=arr.length;i<j;i++)
                {
                    let p = arr[i].split("_");
                    p.length==2 && (this._points = this._points.concat(p))
                }
                */
                this.asyncDraw();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5Shape.prototype, "round", {
            get: function () {
                return this._round ? this._round : '';
            },
            set: function (r) {
                if (r == null || r == 'null')
                    r = '0';
                r = r.replace(/'/g, '');
                var v;
                if (r.indexOf(' ') == -1) {
                    v = parseInt(r);
                    if (v < 0)
                        v = 0;
                    this._round_0 = this._round_1 = this._round_2 = this._round_3 = v;
                    this._round = v + '';
                }
                else {
                    var arr = r.split(' ');
                    switch (arr.length) {
                        case 2:
                            v = parseInt(arr[0]);
                            if (v < 0)
                                v = 0;
                            this._round_0 = this._round_1 = v;
                            v = parseInt(arr[1]);
                            if (v < 0)
                                v = 0;
                            this._round_2 = this._round_3 = v;
                            this._round = arr[0] + ' ' + arr[1];
                            break;
                        case 3:
                            v = parseInt(arr[0]);
                            if (v < 0)
                                v = 0;
                            this._round_0 = v;
                            v = parseInt(arr[1]);
                            if (v < 0)
                                v = 0;
                            this._round_1 = v;
                            v = parseInt(arr[2]);
                            if (v < 0)
                                v = 0;
                            this._round_2 = this._round_3 = v;
                            this._round = arr[0] + ' ' + arr[1] + ' ' + arr[2];
                            break;
                        default:
                            for (var i = 0; i < 4; i++) {
                                v = arr[i] ? parseInt(arr[i]) : 0;
                                if (v < 0)
                                    v = 0;
                                this['_round_' + i] = v;
                            }
                            this._round = arr[0] + ' ' + arr[1] + ' ' + arr[2] + ' ' + arr[3];
                            break;
                    }
                }
                this.asyncDraw();
            },
            enumerable: true,
            configurable: true
        });
        D5Shape.prototype.draw = function () {
            this._graphics.clear();
            var rk = Math.PI / 180;
            switch (this.workMode) {
                case D5Shape.RECT:
                    if (this._round_0 == this._round_1 && this._round_1 == this._round_2 && this._round_2 == this._round_3) {
                        this._graphics.roundRect(this._offX, this._offY, this.realWidth, this.realHeight, this._round_0);
                    }
                    else if (this._round_0 != 0 || this._round_1 != 0 || this._round_2 != 0 || this._round_3 != 0) {
                        var p = { x: this._offX + this._round_0, y: this._offY + this._round_0 };
                        this._graphics.moveTo(p.x, p.y);
                        this._graphics.arc(p.x, p.y, this._round_0, 180 * rk, 270 * rk);
                        p.x += this.realWidth - this._round_1 * 2;
                        p.y -= this._round_1;
                        this._graphics.lineTo(p.x, p.y);
                        this._graphics.arc(p.x, p.y + this._round_1, this._round_1, -90 * rk, 0);
                        p.x += this._round_1;
                        p.y += this.realHeight - this._round_3;
                        this._graphics.lineTo(p.x, p.y);
                        this._graphics.arc(p.x - this._round_3, p.y, this._round_3, 0, 90 * rk);
                        p.x -= this.realWidth - this._round_2;
                        p.y += this._round_3;
                        this._graphics.lineTo(p.x, p.y);
                        this._graphics.arc(p.x, p.y - this._round_2, this._round_2, 90 * rk, 180 * rk);
                        this._graphics.lineTo(this._offX, this._offY + this._round_0);
                    }
                    else {
                        this._graphics.rect(this._offX, this._offY, this.realWidth, this.realHeight);
                    }
                    break;
                case D5Shape.CIRCLE:
                    this._graphics.circle(this._offX, this._offY, this._radius);
                    break;
                case D5Shape.CUSTOM:
                    var temp;
                    var tempX;
                    var tempY;
                    for (var i = 0; i < this._points.length; i++) {
                        temp = this._points[i].split('_');
                        tempX = parseInt(temp[0]);
                        tempY = parseInt(temp[1]);
                        if (i == 0) {
                            this._graphics.moveTo(tempX, tempY);
                        }
                        else {
                            this._graphics.lineTo(tempX, tempY);
                        }
                    }
                    break;
            }
            this._fillColor >= 0 && this._graphics.fill({ color: this._fillColor, alpha: this.drawAlpha });
            this._tickNess > 0 && this._color != -1 && this._graphics.stroke({ width: this._tickNess, color: this._color, alpha: this.lineAlpha });
            if (this._maskName) {
                var target = this.ui[this._maskName];
                target && target.mask && target.mask(this);
            }
        };
        Object.defineProperty(D5Shape.prototype, "fillColor", {
            /**
             *填充颜色
             */
            get: function () {
                return this._fillColor;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * 设置填充色
         */
        D5Shape.prototype.setFillColor = function (value) {
            if (this._fillColor == value)
                return;
            this._fillColor = value;
            this.asyncDraw();
        };
        Object.defineProperty(D5Shape.prototype, "tickNess", {
            /**
             * 线条粗细，0为不显示线条
             */
            get: function () {
                return this._tickNess;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @private
         */
        D5Shape.prototype.setTickNess = function (value) {
            if (this._tickNess == value)
                return;
            this._tickNess = value;
            this.asyncDraw();
        };
        Object.defineProperty(D5Shape.prototype, "color", {
            /**
             * 线条颜色
             */
            get: function () {
                return this._color;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * 设置线条颜色
         */
        D5Shape.prototype.setColor = function (value) {
            if (value == "" || !value)
                value = 0;
            if (this._color == value)
                return;
            this._color = value;
            this.asyncDraw();
        };
        Object.defineProperty(D5Shape.prototype, "offX", {
            /**
             * 偏移坐标x,y
             */
            get: function () {
                return this._offX;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @private
         */
        D5Shape.prototype.setOffX = function (value) {
            if (this._offX == value)
                return;
            this._offX = value;
            this.asyncDraw();
        };
        Object.defineProperty(D5Shape.prototype, "offY", {
            /**
             * 偏移坐标x,y
             */
            get: function () {
                return this._offY;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @private
         */
        D5Shape.prototype.setOffY = function (value) {
            if (this._offY == value)
                return;
            this._offY = value;
            this.asyncDraw();
        };
        Object.defineProperty(D5Shape.prototype, "drawWidth", {
            get: function () {
                return this.realWidth;
            },
            enumerable: true,
            configurable: true
        });
        D5Shape.prototype.clone = function () {
            if (true) {
                var obj = new D5Shape();
                obj._workMode = this._workMode;
                obj._fillColor = this._fillColor;
                obj._tickNess = this._tickNess;
                obj._color = this._color;
                obj._offX = this._offX;
                obj._offY = this._offY;
                obj._radius = this._radius;
                obj.round = this._round;
                obj.setSize(this.realWidth, this.realHeight);
                obj.drawAlpha = this.drawAlpha;
                obj.draw();
            }
            else {
                /*
                var obj:D5Shape = new D5Shape(false);
                obj.setSize(this._staticTex.textureWidth,this._staticTex.textureHeight);
                obj.addChild(new egret.Bitmap(this._staticTex));
                */
            }
            return obj;
        };
        D5Shape.prototype.setDrawWidth = function (value) {
            if (this.realWidth == value)
                return;
            this.realWidth = value;
            this.asyncDraw();
        };
        Object.defineProperty(D5Shape.prototype, "drawHeight", {
            get: function () {
                return this.realHeight;
            },
            enumerable: true,
            configurable: true
        });
        D5Shape.prototype.setDrawHeight = function (value) {
            if (this.realHeight == value)
                return;
            this.realHeight = value;
            this.asyncDraw();
        };
        Object.defineProperty(D5Shape.prototype, "radius", {
            get: function () {
                return this._radius;
            },
            enumerable: true,
            configurable: true
        });
        D5Shape.prototype.setRadius = function (value) {
            if (this._radius == value)
                return;
            this._radius = value;
            this.asyncDraw();
        };
        Object.defineProperty(D5Shape.prototype, "workMode", {
            get: function () {
                return this._workMode;
            },
            set: function (value) {
                this._workMode = value;
                this.asyncDraw();
            },
            enumerable: true,
            configurable: true
        });
        D5Shape.prototype.dispose = function () {
            this._graphics.clear();
        };
        /**
         * 工作模式矩形
         */
        D5Shape.RECT = 0;
        /**
         * 工作模式圆
         */
        D5Shape.CIRCLE = 1;
        /**
         * 自定义填充
         */
        D5Shape.CUSTOM = 2;
        return D5Shape;
    }(d5.D5Component));
    d5.D5Shape = D5Shape;
    __reflect(D5Shape.prototype, "d5.D5Shape");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5Bitmap = (function (_super) {
        __extends(D5Bitmap, _super);
        function D5Bitmap(anchorX, anchorY) {
            if (anchorX === void 0) { anchorX = 0; }
            if (anchorY === void 0) { anchorY = 0; }
            var _this = _super.call(this) || this;
            _this._anchorX = anchorX;
            _this._anchorY = anchorY;
            return _this;
        }
        D5Bitmap.prototype.clone = function () {
            var newone = new D5Bitmap();
            newone.init.apply(newone, this._initArgs);
            newone.setSize(this.width, this.height);
            //trace(this.width,this.height,"D5Bitmap");
            return newone;
        };
        D5Bitmap.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            _super.prototype.init.apply(this, args);
            var uiresource = args[0];
            var skinId = args[1];
            if (!skinId)
                throw new Error("[D5Bitmap] skinId is not set (" + skinId + ")");
            if (uiresource == null)
                uiresource = d5.D5Component.uiresource;
            if (!uiresource || !uiresource.textures || !uiresource.textures[skinId]) {
                this.setSkin(skinId);
                return;
            }
            this._monitor.addChild(this._bitmap = new PIXI.Sprite(uiresource.textures[skinId]));
        };
        D5Bitmap.prototype.setSkin = function (path) {
            var _this = this;
            var getskin = function () { return __awaiter(_this, void 0, void 0, function () {
                var texture;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, PIXI.Assets.load(path)];
                        case 1:
                            texture = _a.sent();
                            if (this._bitmap) {
                                this._bitmap.texture = texture;
                            }
                            else {
                                this._bitmap = new PIXI.Sprite(texture);
                                this._monitor.addChild(this._bitmap);
                                !isNaN(this._waitW) && this.setSize(this._waitW, this._waitH);
                            }
                            this._bitmap.anchor.set(this._anchorX, this._anchorY);
                            return [2 /*return*/];
                    }
                });
            }); };
            getskin();
        };
        D5Bitmap.prototype.mask = function (v) {
            this._bitmap.mask = v.graphics;
        };
        D5Bitmap.prototype.setSize = function (w, h) {
            if (this._bitmap) {
                this._bitmap.width = w;
                this._bitmap.height = h;
            }
            else {
                this._waitW = w;
                this._waitH = h;
            }
            _super.prototype.setSize.call(this, w, h);
        };
        return D5Bitmap;
    }(d5.D5Component));
    d5.D5Bitmap = D5Bitmap;
    __reflect(D5Bitmap.prototype, "d5.D5Bitmap");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    // @ts-ignore
    var D5Button = (function (_super) {
        __extends(D5Button, _super);
        function D5Button() {
            var _this = _super.call(this) || this;
            _this._textures = [];
            _this._nowStatus = 0;
            return _this;
        }
        Object.defineProperty(D5Button.prototype, "enabled", {
            get: function () {
                return this._nowStatus != 3;
            },
            set: function (v) {
                this.setStatus(v ? 0 : 3);
                if (v) {
                    this.touchEnable = true;
                }
                else {
                    this.touchEnable = false;
                }
            },
            enumerable: true,
            configurable: true
        });
        D5Button.prototype.clone = function () {
            var newone = new D5Button();
            newone.init.apply(newone, this._initArgs);
            newone.setSize(this.width, this.height);
            newone.label = this._lable.text;
            return newone;
        };
        D5Button.prototype.once = function (event, listener) {
            if (event.indexOf('pointer') != -1) {
                this.touchEnable = true;
            }
            _super.prototype.once.call(this, event, listener);
        };
        D5Button.prototype.addEventListener = function (event, listener) {
            if (event.indexOf('pointer') != -1) {
                this.touchEnable = true;
            }
            _super.prototype.addEventListener.call(this, event, listener, "pointer");
        };
        D5Button.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            _super.prototype.init.apply(this, args);
            var uiresource = args[0];
            var skinId = args[1];
            if (!skinId)
                throw new Error("[D5MirrorBox] skinId is not set (" + skinId + ")");
            if (uiresource == null)
                uiresource = d5.D5Component.uiresource;
            if (!uiresource || !uiresource.textures || !uiresource.textures[skinId + ".default"]) {
                console.log("Can not find uiresource " + skinId + ' in ' + uiresource);
                return;
            }
            this._textures = [];
            this._textures.push(uiresource.textures[skinId + ".default"]);
            this._textures.push(uiresource.textures[skinId + ".over"]);
            this._textures.push(uiresource.textures[skinId + ".tap"]);
            this._textures.push(uiresource.textures[skinId + ".disable"]);
            this._monitor.addChild(this._bitmap = new PIXI.Sprite(this._textures[0]));
        };
        D5Button.prototype.setStatus = function (id) {
            if (id < 0)
                id = 0;
            if (id > 3)
                id = 3;
            try {
                this._nowStatus = id;
                this._bitmap.texture = this._textures[id];
            }
            catch (e) { }
        };
        Object.defineProperty(D5Button.prototype, "status", {
            get: function () {
                return this._nowStatus;
            },
            enumerable: true,
            configurable: true
        });
        D5Button.prototype.setSize = function (w, h) {
            this._bitmap.width = w;
            this._bitmap.height = h;
            _super.prototype.setSize.call(this, w, h);
        };
        Object.defineProperty(D5Button.prototype, "label", {
            set: function (v) {
                if (this._lable == null) {
                    this._lable = new d5.D5Text();
                    this._lable.init({ textID: v, textValue: v, fontFamily: '', fontColor: 0xffffff, fontSize: D5Button.default_label_size, alignType: 1, width: this.realWidth, height: this.realHeight });
                    this.addChild(this._lable);
                }
                else {
                    this._lable.text = v;
                }
            },
            enumerable: true,
            configurable: true
        });
        D5Button.default_label_size = 12;
        return D5Button;
    }(d5.D5Component));
    d5.D5Button = D5Button;
    __reflect(D5Button.prototype, "d5.D5Button");
    var D5RadioBtn = (function (_super) {
        __extends(D5RadioBtn, _super);
        function D5RadioBtn() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this._labelPadding = 10;
            return _this;
        }
        Object.defineProperty(D5RadioBtn.prototype, "groupName", {
            set: function (v) {
                this._groupName = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5RadioBtn.prototype, "selected", {
            get: function () {
                return this._selected;
            },
            set: function (v) {
                this._selected = v;
                this.setStatus(v ? 2 : 0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5RadioBtn.prototype, "labelPadding", {
            set: function (v) {
                this._labelPadding = v;
                if (this._lable)
                    this._lable.x = this._bitmap.width + this._labelPadding;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5RadioBtn.prototype, "label", {
            set: function (v) {
                if (this._lable == null) {
                    this._lable = new d5.D5Text();
                    this._lable.init({ textID: v, textValue: v, fontFamily: '', fontColor: 0xffffff, fontSize: D5Button.default_label_size, width: this.realWidth });
                    this._lable.x = this._bitmap.width + this._labelPadding;
                    this.addChild(this._lable);
                }
            },
            enumerable: true,
            configurable: true
        });
        D5RadioBtn.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            _super.prototype.init.apply(this, args);
            var that = this;
            that.addEventListener(d5.TouchEvent.TOUCH_TAP, function () {
                if (that._groupName != null) {
                    // 单选
                    if (that._selected)
                        return;
                    for (var i = 0, j = that.parent.children.length; i < j; i++) {
                        var btn = that.parent.getChildAt(i);
                        if (btn.d5component && btn.d5component._groupName == that._groupName) {
                            btn.d5component.selected = false;
                        }
                    }
                    that.selected = true;
                    that.dispathEvent(d5.Event.CHANGE, true);
                }
                else {
                    // 多选
                    that.selected = !that._selected;
                    that.dispathEvent(d5.Event.CHANGE, that._selected);
                }
            });
        };
        return D5RadioBtn;
    }(D5Button));
    d5.D5RadioBtn = D5RadioBtn;
    __reflect(D5RadioBtn.prototype, "d5.D5RadioBtn");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5Window = (function (_super) {
        __extends(D5Window, _super);
        function D5Window() {
            return _super.call(this) || this;
        }
        D5Window.prototype.clone = function () {
            var newone = new D5Window();
            newone.init.apply(newone, this._initArgs);
            newone.setSize(this.width, this.height);
            return newone;
        };
        D5Window.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            _super.prototype.init.apply(this, args);
            var uiresource = args[0];
            var skinId = args[1];
            this._cut0 = args[2];
            this._cut1 = args[3];
            if (!skinId)
                throw new Error("[D5Window] skinId is not set (" + skinId + ")");
            if (uiresource == null)
                uiresource = d5.D5Component.uiresource;
            if (!uiresource || !uiresource.textures || !uiresource.textures[skinId + '.m']) {
                console.log("Can not find uiresource " + skinId + '.m in ' + uiresource);
                return;
            }
            else {
                this._monitor.addChild(this._lt = new PIXI.Sprite(uiresource.textures[skinId + '.lt']));
                this._monitor.addChild(this._t = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.t'] }));
                this._monitor.addChild(this._rt = new PIXI.Sprite(uiresource.textures[skinId + '.rt']));
                this._monitor.addChild(this._l = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.l'] }));
                this._monitor.addChild(this._m = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.m'] }));
                this._monitor.addChild(this._r = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.r'] }));
                this._monitor.addChild(this._lb = new PIXI.Sprite(uiresource.textures[skinId + '.lb']));
                this._monitor.addChild(this._b = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.b'] }));
                this._monitor.addChild(this._rb = new PIXI.Sprite(uiresource.textures[skinId + '.rb']));
            }
        };
        D5Window.prototype.setSize = function (w, h) {
            this._b.x = this._m.x = this._t.x = this._cut0.x;
            this._rb.x = this._r.x = this._rt.x = w - this._rt.width;
            this._r.y = this._l.y = this._m.y = this._cut0.y;
            this._lb.y = this._b.y = this._rb.y = h - this._b.height;
            this._t.width = this._m.width = this._b.width = w - this._t.x - this._r.width;
            this._l.height = this._m.height = this._r.height = h - this._m.y - this._b.height;
            _super.prototype.setSize.call(this, w, h);
        };
        return D5Window;
    }(d5.D5Component));
    d5.D5Window = D5Window;
    __reflect(D5Window.prototype, "d5.D5Window");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5MirrorBox = (function (_super) {
        __extends(D5MirrorBox, _super);
        function D5MirrorBox() {
            return _super.call(this) || this;
        }
        D5MirrorBox.prototype.clone = function () {
            var newone = new D5MirrorBox();
            newone.init.apply(newone, this._initArgs);
            newone.setSize(this.width, this.height);
            return newone;
        };
        D5MirrorBox.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            _super.prototype.init.apply(this, args);
            var uiresource = args[0];
            var skinId = args[1];
            this._cut0 = args[2];
            this._cut1 = args[3];
            if (!skinId)
                throw new Error("[D5MirrorBox] skinId is not set (" + skinId + ")");
            if (uiresource == null)
                uiresource = d5.D5Component.uiresource;
            if (!uiresource || !uiresource.textures || !uiresource.textures[skinId + '.lt']) {
                console.log("Can not find uiresource " + skinId + '.lt in ' + uiresource);
                return;
            }
            else {
                this._monitor.addChild(this._lt = new PIXI.Sprite(uiresource.textures[skinId + '.lt']));
                this._monitor.addChild(this._rt = new PIXI.Sprite(uiresource.textures[skinId + '.lt']));
                this._monitor.addChild(this._lb = new PIXI.Sprite(uiresource.textures[skinId + '.lt']));
                this._monitor.addChild(this._rb = new PIXI.Sprite(uiresource.textures[skinId + '.lt']));
                this._monitor.addChild(this._t = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.rt'] }));
                this._monitor.addChild(this._b = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.rt'] }));
                this._monitor.addChild(this._l = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.lb'] }));
                this._monitor.addChild(this._r = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.lb'] }));
                this._monitor.addChild(this._m = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.rb'] }));
                this._b.updateTransform({ scaleY: -1 });
                this._lb.updateTransform({ scaleY: -1 });
                this._rb.updateTransform({ scaleY: -1 });
                this._r.updateTransform({ scaleX: -1 });
                this._rt.updateTransform({ scaleX: -1 });
                this._rb.updateTransform({ scaleX: -1 });
                //this._b.scaley = this._lb.scaley = this._rb.scaley = -1;
                //this._r.scalex = this._rt.scalex = this._rb.scalex = -1;
            }
        };
        D5MirrorBox.prototype.setSize = function (w, h) {
            this._t.x = this._m.x = this._b.x = this._lt.width;
            this._rt.x = this._r.x = this._rb.x = w;
            this._l.y = this._m.y = this._r.y = this._lt.height;
            this._lb.y = this._b.y = this._rb.y = h;
            this._m.width = this._t.width = this._b.width = w - this._lt.width * 2;
            this._m.height = this._l.height = this._r.height = h - this._lt.height * 2;
            //this._monitor.cacheAsTexture = true;
            _super.prototype.setSize.call(this, w, h);
        };
        return D5MirrorBox;
    }(d5.D5Component));
    d5.D5MirrorBox = D5MirrorBox;
    __reflect(D5MirrorBox.prototype, "d5.D5MirrorBox");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5MirrorLoop = (function (_super) {
        __extends(D5MirrorLoop, _super);
        function D5MirrorLoop() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        D5MirrorLoop.prototype.clone = function () {
            var newone = new D5MirrorLoop();
            newone.init.apply(newone, this._initArgs);
            newone.setSize(this.width, this.height);
            return newone;
        };
        D5MirrorLoop.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            _super.prototype.init.apply(this, args);
            var uiresource = args[0];
            var skinId = args[1];
            var _cut = args[2];
            this._pin_position = args[3];
            this._mode = parseInt(_cut.mode);
            if (!skinId)
                throw new Error("[D5MirrorBox] skinId is not set (" + skinId + ")");
            if (uiresource == null)
                uiresource = d5.D5Component.uiresource;
            if (!uiresource || !uiresource.textures || !uiresource.textures[skinId + '.l']) {
                console.log("Can not find uiresource " + skinId + '.l in ' + uiresource);
                return;
            }
            else {
                this._monitor.addChild(this._front = new PIXI.Sprite(uiresource.textures[skinId + '.l']));
                this._monitor.addChild(this._ender = new PIXI.Sprite(uiresource.textures[skinId + '.l']));
                this._monitor.addChild(this._center = new PIXI.TilingSprite({ texture: uiresource.textures[skinId + '.r'] }));
                this._ender.updateTransform({ scaleX: -1 });
            }
        };
        D5MirrorLoop.prototype.setPin = function (val) {
            this._pin_position = val;
        };
        D5MirrorLoop.prototype.setSize = function (w, h) {
            var targetSize;
            if (this._mode == 0) {
                this._center.x = this._front.width;
                targetSize = w - this._front.width * 2;
                targetSize < 0 && (targetSize = 0);
                targetSize > 0 ? (this._center.width = targetSize) : (this._center.visible = false);
                this._ender.x = this._center.x + targetSize + this._front.width;
            }
            else {
                this._center.y = this._front.height;
                targetSize = h - this._front.height * 2;
                targetSize < 0 && (targetSize = 0);
                targetSize > 0 ? (this._center.height = targetSize) : (this._center.visible = false);
                this._ender.y = this._center.y + targetSize + this._front.height;
            }
            _super.prototype.setSize.call(this, w, h);
        };
        return D5MirrorLoop;
    }(d5.D5Component));
    d5.D5MirrorLoop = D5MirrorLoop;
    __reflect(D5MirrorLoop.prototype, "d5.D5MirrorLoop");
})(d5 || (d5 = {}));
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
var d5;
(function (d5) {
    /**
     * @language en_US
     * The Endian class contains values that denote the byte order used to represent multibyte numbers.
     * The byte order is either bigEndian (most significant byte first) or littleEndian (least significant byte first).
     * @version Egret 2.4
     * @platform Web,Native
     */
    /**
     * @language zh_CN
     * Endian 类中包含一些值，它们表示用于表示多字节数字的字节顺序。
     * 字节顺序为 bigEndian（最高有效字节位于最前）或 littleEndian（最低有效字节位于最前）。
     * @version Egret 2.4
     * @platform Web,Native
     */
    var Endian = (function () {
        function Endian() {
        }
        /**
         * @language en_US
         * Indicates the least significant byte of the multibyte number appears first in the sequence of bytes.
         * The hexadecimal number 0x12345678 has 4 bytes (2 hexadecimal digits per byte). The most significant byte is 0x12. The least significant byte is 0x78. (For the equivalent decimal number, 305419896, the most significant digit is 3, and the least significant digit is 6).
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 表示多字节数字的最低有效字节位于字节序列的最前面。
         * 十六进制数字 0x12345678 包含 4 个字节（每个字节包含 2 个十六进制数字）。最高有效字节为 0x12。最低有效字节为 0x78。（对于等效的十进制数字 305419896，最高有效数字是 3，最低有效数字是 6）。
         * @version Egret 2.4
         * @platform Web,Native
         */
        Endian.LITTLE_ENDIAN = "littleEndian";
        /**
         * @language en_US
         * Indicates the most significant byte of the multibyte number appears first in the sequence of bytes.
         * The hexadecimal number 0x12345678 has 4 bytes (2 hexadecimal digits per byte).  The most significant byte is 0x12. The least significant byte is 0x78. (For the equivalent decimal number, 305419896, the most significant digit is 3, and the least significant digit is 6).
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 表示多字节数字的最高有效字节位于字节序列的最前面。
         * 十六进制数字 0x12345678 包含 4 个字节（每个字节包含 2 个十六进制数字）。最高有效字节为 0x12。最低有效字节为 0x78。（对于等效的十进制数字 305419896，最高有效数字是 3，最低有效数字是 6）。
         * @version Egret 2.4
         * @platform Web,Native
         */
        Endian.BIG_ENDIAN = "bigEndian";
        return Endian;
    }());
    d5.Endian = Endian;
    __reflect(Endian.prototype, "d5.Endian");
    /**
     * @language en_US
     * The ByteArray class provides methods and attributes for optimized reading and writing as well as dealing with binary data.
     * Note: The ByteArray class is applied to the advanced developers who need to access data at the byte layer.
     * @version Egret 2.4
     * @platform Web,Native
     * @includeExample egret/utils/ByteArray.ts
     */
    /**
     * @language zh_CN
     * ByteArray 类提供用于优化读取、写入以及处理二进制数据的方法和属性。
     * 注意：ByteArray 类适用于需要在字节层访问数据的高级开发人员。
     * @version Egret 2.4
     * @platform Web,Native
     * @includeExample egret/utils/ByteArray.ts
     */
    var ByteArray = (function () {
        /**
         * @version Egret 2.4
         * @platform Web,Native
         */
        function ByteArray(buffer) {
            /**
             * @private
             */
            this.BUFFER_EXT_SIZE = 0; //Buffer expansion size
            /**
             * @private
             */
            this.EOF_byte = -1;
            /**
             * @private
             */
            this.EOF_code_point = -1;
            this._setArrayBuffer(buffer || new ArrayBuffer(this.BUFFER_EXT_SIZE));
            this.endian = Endian.BIG_ENDIAN;
        }
        /**
         * @private
         * @param buffer
         */
        ByteArray.prototype._setArrayBuffer = function (buffer) {
            this.write_position = buffer.byteLength;
            this.data = new DataView(buffer);
            this._position = 0;
        };
        /**
         * @deprecated
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.setArrayBuffer = function (buffer) {
        };
        Object.defineProperty(ByteArray.prototype, "buffer", {
            get: function () {
                return this.data.buffer;
            },
            /**
             * @private
             */
            set: function (value) {
                this.data = new DataView(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ByteArray.prototype, "dataView", {
            /**
             * @private
             * @version Egret 2.4
             * @platform Web,Native
             */
            get: function () {
                return this.data;
            },
            /**
             * @private
             */
            set: function (value) {
                this.data = value;
                this.write_position = value.byteLength;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ByteArray.prototype, "bufferOffset", {
            /**
             * @private
             */
            get: function () {
                return this.data.byteOffset;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ByteArray.prototype, "position", {
            /**
             * @language en_US
             * The current position of the file pointer (in bytes) to move or return to the ByteArray object. The next time you start reading reading method call in this position, or will start writing in this position next time call a write method.
             * @version Egret 2.4
             * @platform Web,Native
             */
            /**
             * @language zh_CN
             * 将文件指针的当前位置（以字节为单位）移动或返回到 ByteArray 对象中。下一次调用读取方法时将在此位置开始读取，或者下一次调用写入方法时将在此位置开始写入。
             * @version Egret 2.4
             * @platform Web,Native
             */
            get: function () {
                return this._position;
            },
            set: function (value) {
                //if (this._position < value) {
                //    if (!this.validate(value - this._position)) {
                //        return;
                //    }
                //}
                this._position = value;
                this.write_position = value > this.write_position ? value : this.write_position;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ByteArray.prototype, "length", {
            /**
             * @language en_US
             * The length of the ByteArray object (in bytes).
                      * If the length is set to be larger than the current length, the right-side zero padding byte array.
                      * If the length is set smaller than the current length, the byte array is truncated.
             * @version Egret 2.4
             * @platform Web,Native
             */
            /**
             * @language zh_CN
             * ByteArray 对象的长度（以字节为单位）。
             * 如果将长度设置为大于当前长度的值，则用零填充字节数组的右侧。
             * 如果将长度设置为小于当前长度的值，将会截断该字节数组。
             * @version Egret 2.4
             * @platform Web,Native
             */
            get: function () {
                return this.write_position;
            },
            set: function (value) {
                this.write_position = value;
                var tmp = new Uint8Array(new ArrayBuffer(value));
                var byteLength = this.data.buffer.byteLength;
                if (byteLength > value) {
                    this._position = value;
                }
                var length = Math.min(byteLength, value);
                tmp.set(new Uint8Array(this.data.buffer, 0, length));
                this.buffer = tmp.buffer;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ByteArray.prototype, "bytesAvailable", {
            /**
             * @language en_US
             * The number of bytes that can be read from the current position of the byte array to the end of the array data.
             * When you access a ByteArray object, the bytesAvailable property in conjunction with the read methods each use to make sure you are reading valid data.
             * @version Egret 2.4
             * @platform Web,Native
             */
            /**
             * @language zh_CN
             * 可从字节数组的当前位置到数组末尾读取的数据的字节数。
             * 每次访问 ByteArray 对象时，将 bytesAvailable 属性与读取方法结合使用，以确保读取有效的数据。
             * @version Egret 2.4
             * @platform Web,Native
             */
            get: function () {
                return this.data.byteLength - this._position;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @language en_US
         * Clears the contents of the byte array and resets the length and position properties to 0.
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 清除字节数组的内容，并将 length 和 position 属性重置为 0。
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.clear = function () {
            this._setArrayBuffer(new ArrayBuffer(this.BUFFER_EXT_SIZE));
        };
        /**
         * @language en_US
         * Read a Boolean value from the byte stream. Read a simple byte. If the byte is non-zero, it returns true; otherwise, it returns false.
         * @return If the byte is non-zero, it returns true; otherwise, it returns false.
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取布尔值。读取单个字节，如果字节非零，则返回 true，否则返回 false
         * @return 如果字节不为零，则返回 true，否则返回 false
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readBoolean = function () {
            if (!this.validate(ByteArray.SIZE_OF_BOOLEAN))
                return null;
            return this.data.getUint8(this.position++) != 0;
        };
        /**
         * @language en_US
         * Read signed bytes from the byte stream.
         * @return An integer ranging from -128 to 127
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取带符号的字节
         * @return 介于 -128 和 127 之间的整数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readByte = function () {
            if (!this.validate(ByteArray.SIZE_OF_INT8))
                return null;
            return this.data.getInt8(this.position++);
        };
        /**
         * @language en_US
         * Read data byte number specified by the length parameter from the byte stream. Starting from the position specified by offset, read bytes into the ByteArray object specified by the bytes parameter, and write bytes into the target ByteArray
         * @param bytes ByteArray object that data is read into
         * @param offset Offset (position) in bytes. Read data should be written from this position
         * @param length Byte number to be read Default value 0 indicates reading all available data
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取 length 参数指定的数据字节数。从 offset 指定的位置开始，将字节读入 bytes 参数指定的 ByteArray 对象中，并将字节写入目标 ByteArray 中
         * @param bytes 要将数据读入的 ByteArray 对象
         * @param offset bytes 中的偏移（位置），应从该位置写入读取的数据
         * @param length 要读取的字节数。默认值 0 导致读取所有可用的数据
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readBytes = function (bytes, offset, length) {
            if (offset === void 0) { offset = 0; }
            if (length === void 0) { length = 0; }
            if (length == 0) {
                length = this.bytesAvailable;
            }
            else if (!this.validate(length)) {
                return null;
            }
            if (bytes) {
                bytes.validateBuffer(offset + length);
            }
            else {
                bytes = new ByteArray(new ArrayBuffer(offset + length));
            }
            //This method is expensive
            for (var i = 0; i < length; i++) {
                bytes.data.setUint8(i + offset, this.data.getUint8(this.position++));
            }
        };
        /**
         * @language en_US
         * Read an IEEE 754 double-precision (64 bit) floating point number from the byte stream
         * @return Double-precision (64 bit) floating point number
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取一个 IEEE 754 双精度（64 位）浮点数
         * @return 双精度（64 位）浮点数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readDouble = function () {
            if (!this.validate(ByteArray.SIZE_OF_FLOAT64))
                return null;
            var value = this.data.getFloat64(this.position, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_FLOAT64;
            return value;
        };
        /**
         * @language en_US
         * Read an IEEE 754 single-precision (32 bit) floating point number from the byte stream
         * @return Single-precision (32 bit) floating point number
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取一个 IEEE 754 单精度（32 位）浮点数
         * @return 单精度（32 位）浮点数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readFloat = function () {
            if (!this.validate(ByteArray.SIZE_OF_FLOAT32))
                return null;
            var value = this.data.getFloat32(this.position, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_FLOAT32;
            return value;
        };
        /**
         * @language en_US
         * Read a 32-bit signed integer from the byte stream.
         * @return A 32-bit signed integer ranging from -2147483648 to 2147483647
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取一个带符号的 32 位整数
         * @return 介于 -2147483648 和 2147483647 之间的 32 位带符号整数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readInt = function () {
            if (!this.validate(ByteArray.SIZE_OF_INT32))
                return null;
            var value = this.data.getInt32(this.position, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_INT32;
            return value;
        };
        ///**
        // * 使用指定的字符集从字节流中读取指定长度的多字节字符串
        // * @param length 要从字节流中读取的字节数
        // * @param charSet 表示用于解释字节的字符集的字符串。可能的字符集字符串包括 "shift-jis"、"cn-gb"、"iso-8859-1"”等
        // * @return UTF-8 编码的字符串
        // * @method egret.ByteArray#readMultiByte
        // */
        //public readMultiByte(length:number, charSet?:string):string {
        //    if (!this.validate(length)) return null;
        //
        //    return "";
        //}
        /**
         * @language en_US
         * Read a 16-bit signed integer from the byte stream.
         * @return A 16-bit signed integer ranging from -32768 to 32767
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取一个带符号的 16 位整数
         * @return 介于 -32768 和 32767 之间的 16 位带符号整数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readShort = function () {
            if (!this.validate(ByteArray.SIZE_OF_INT16))
                return null;
            var value = this.data.getInt16(this.position, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_INT16;
            return value;
        };
        /**
         * @language en_US
         * Read unsigned bytes from the byte stream.
         * @return A 32-bit unsigned integer ranging from 0 to 255
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取无符号的字节
         * @return 介于 0 和 255 之间的 32 位无符号整数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readUnsignedByte = function () {
            if (!this.validate(ByteArray.SIZE_OF_UINT8))
                return null;
            return this.data.getUint8(this.position++);
        };
        /**
         * @language en_US
         * Read a 32-bit unsigned integer from the byte stream.
         * @return A 32-bit unsigned integer ranging from 0 to 4294967295
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取一个无符号的 32 位整数
         * @return 介于 0 和 4294967295 之间的 32 位无符号整数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readUnsignedInt = function () {
            if (!this.validate(ByteArray.SIZE_OF_UINT32))
                return null;
            var value = this.data.getUint32(this.position, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_UINT32;
            return value;
        };
        /**
         * @language en_US
         * Read a 16-bit unsigned integer from the byte stream.
         * @return A 16-bit unsigned integer ranging from 0 to 65535
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取一个无符号的 16 位整数
         * @return 介于 0 和 65535 之间的 16 位无符号整数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readUnsignedShort = function () {
            if (!this.validate(ByteArray.SIZE_OF_UINT16))
                return null;
            var value = this.data.getUint16(this.position, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_UINT16;
            return value;
        };
        /**
         * @language en_US
         * Read a UTF-8 character string from the byte stream Assume that the prefix of the character string is a short unsigned integer (use byte to express length)
         * @return UTF-8 character string
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取一个 UTF-8 字符串。假定字符串的前缀是无符号的短整型（以字节表示长度）
         * @return UTF-8 编码的字符串
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readUTF = function () {
            if (!this.validate(ByteArray.SIZE_OF_UINT16))
                return null;
            var length = this.data.getUint16(this.position, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_UINT16;
            if (length > 0) {
                return this.readUTFBytes(length);
            }
            else {
                return "";
            }
        };
        /**
         * @language en_US
         * Read a UTF-8 byte sequence specified by the length parameter from the byte stream, and then return a character string
         * @param Specify a short unsigned integer of the UTF-8 byte length
         * @return A character string consists of UTF-8 bytes of the specified length
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 从字节流中读取一个由 length 参数指定的 UTF-8 字节序列，并返回一个字符串
         * @param length 指明 UTF-8 字节长度的无符号短整型数
         * @return 由指定长度的 UTF-8 字节组成的字符串
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.readUTFBytes = function (length) {
            if (!this.validate(length))
                return null;
            var bytes = new Uint8Array(this.buffer, this.bufferOffset + this.position, length);
            this.position += length;
            /*let bytes: Uint8Array = new Uint8Array(new ArrayBuffer(length));
             for (let i = 0; i < length; i++) {
             bytes[i] = this.data.getUint8(this.position++);
             }*/
            return this.decodeUTF8(bytes);
        };
        /**
         * @language en_US
         * Write a Boolean value. A single byte is written according to the value parameter. If the value is true, write 1; if the value is false, write 0.
         * @param value A Boolean value determining which byte is written. If the value is true, write 1; if the value is false, write 0.
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 写入布尔值。根据 value 参数写入单个字节。如果为 true，则写入 1，如果为 false，则写入 0
         * @param value 确定写入哪个字节的布尔值。如果该参数为 true，则该方法写入 1；如果该参数为 false，则该方法写入 0
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeBoolean = function (value) {
            this.validateBuffer(ByteArray.SIZE_OF_BOOLEAN);
            this.data.setUint8(this.position++, value ? 1 : 0);
        };
        /**
         * @language en_US
         * Write a byte into the byte stream
         * The low 8 bits of the parameter are used. The high 24 bits are ignored.
         * @param value A 32-bit integer. The low 8 bits will be written into the byte stream
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 在字节流中写入一个字节
         * 使用参数的低 8 位。忽略高 24 位
         * @param value 一个 32 位整数。低 8 位将被写入字节流
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeByte = function (value) {
            this.validateBuffer(ByteArray.SIZE_OF_INT8);
            this.data.setInt8(this.position++, value);
        };
        /**
         * @language en_US
         * Write the byte sequence that includes length bytes in the specified byte array, bytes, (starting at the byte specified by offset, using a zero-based index), into the byte stream
         * If the length parameter is omitted, the default length value 0 is used and the entire buffer starting at offset is written. If the offset parameter is also omitted, the entire buffer is written
         * If the offset or length parameter is out of range, they are clamped to the beginning and end of the bytes array.
         * @param bytes ByteArray Object
         * @param offset A zero-based index specifying the position into the array to begin writing
         * @param length An unsigned integer specifying how far into the buffer to write
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 将指定字节数组 bytes（起始偏移量为 offset，从零开始的索引）中包含 length 个字节的字节序列写入字节流
         * 如果省略 length 参数，则使用默认长度 0；该方法将从 offset 开始写入整个缓冲区。如果还省略了 offset 参数，则写入整个缓冲区
         * 如果 offset 或 length 超出范围，它们将被锁定到 bytes 数组的开头和结尾
         * @param bytes ByteArray 对象
         * @param offset 从 0 开始的索引，表示在数组中开始写入的位置
         * @param length 一个无符号整数，表示在缓冲区中的写入范围
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeBytes = function (bytes, offset, length) {
            if (offset === void 0) { offset = 0; }
            if (length === void 0) { length = 0; }
            var writeLength;
            if (offset < 0) {
                return;
            }
            if (length < 0) {
                return;
            }
            else if (length == 0) {
                writeLength = bytes.length - offset;
            }
            else {
                writeLength = Math.min(bytes.length - offset, length);
            }
            if (writeLength > 0) {
                this.validateBuffer(writeLength);
                var tmp_data = new DataView(bytes.buffer);
                var length_2 = writeLength;
                var BYTES_OF_UINT32 = 4;
                for (; length_2 > BYTES_OF_UINT32; length_2 -= BYTES_OF_UINT32) {
                    this.data.setUint32(this._position, tmp_data.getUint32(offset));
                    this.position += BYTES_OF_UINT32;
                    offset += BYTES_OF_UINT32;
                }
                for (; length_2 > 0; length_2--) {
                    this.data.setUint8(this.position++, tmp_data.getUint8(offset++));
                }
            }
        };
        /**
         * @language en_US
         * Write an IEEE 754 double-precision (64 bit) floating point number into the byte stream
         * @param value Double-precision (64 bit) floating point number
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 在字节流中写入一个 IEEE 754 双精度（64 位）浮点数
         * @param value 双精度（64 位）浮点数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeDouble = function (value) {
            this.validateBuffer(ByteArray.SIZE_OF_FLOAT64);
            this.data.setFloat64(this.position, value, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_FLOAT64;
        };
        /**
         * @language en_US
         * Write an IEEE 754 single-precision (32 bit) floating point number into the byte stream
         * @param value Single-precision (32 bit) floating point number
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 在字节流中写入一个 IEEE 754 单精度（32 位）浮点数
         * @param value 单精度（32 位）浮点数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeFloat = function (value) {
            this.validateBuffer(ByteArray.SIZE_OF_FLOAT32);
            this.data.setFloat32(this.position, value, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_FLOAT32;
        };
        /**
         * @language en_US
         * Write a 32-bit signed integer into the byte stream
         * @param value An integer to be written into the byte stream
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 在字节流中写入一个带符号的 32 位整数
         * @param value 要写入字节流的整数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeInt = function (value) {
            this.validateBuffer(ByteArray.SIZE_OF_INT32);
            this.data.setInt32(this.position, value, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_INT32;
        };
        /**
         * @language en_US
         * Write a 16-bit integer into the byte stream. The low 16 bits of the parameter are used. The high 16 bits are ignored.
         * @param value A 32-bit integer. Its low 16 bits will be written into the byte stream
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 在字节流中写入一个 16 位整数。使用参数的低 16 位。忽略高 16 位
         * @param value 32 位整数，该整数的低 16 位将被写入字节流
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeShort = function (value) {
            this.validateBuffer(ByteArray.SIZE_OF_INT16);
            this.data.setInt16(this.position, value, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_INT16;
        };
        /**
         * @language en_US
         * Write a 32-bit unsigned integer into the byte stream
         * @param value An unsigned integer to be written into the byte stream
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 在字节流中写入一个无符号的 32 位整数
         * @param value 要写入字节流的无符号整数
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeUnsignedInt = function (value) {
            this.validateBuffer(ByteArray.SIZE_OF_UINT32);
            this.data.setUint32(this.position, value, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_UINT32;
        };
        /**
         * @language en_US
         * Write a 16-bit unsigned integer into the byte stream
         * @param value An unsigned integer to be written into the byte stream
         * @version Egret 2.5
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 在字节流中写入一个无符号的 16 位整数
         * @param value 要写入字节流的无符号整数
         * @version Egret 2.5
         * @platform Web,Native
         */
        ByteArray.prototype.writeUnsignedShort = function (value) {
            this.validateBuffer(ByteArray.SIZE_OF_UINT16);
            this.data.setUint16(this.position, value, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_UINT16;
        };
        /**
         * @language en_US
         * Write a UTF-8 string into the byte stream. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string
         * @param value Character string value to be written
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 将 UTF-8 字符串写入字节流。先写入以字节表示的 UTF-8 字符串长度（作为 16 位整数），然后写入表示字符串字符的字节
         * @param value 要写入的字符串值
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeUTF = function (value) {
            var utf8bytes = this.encodeUTF8(value);
            var length = utf8bytes.length;
            this.validateBuffer(ByteArray.SIZE_OF_UINT16 + length);
            this.data.setUint16(this.position, length, this.endian == Endian.LITTLE_ENDIAN);
            this.position += ByteArray.SIZE_OF_UINT16;
            this._writeUint8Array(utf8bytes, false);
        };
        /**
         * @language en_US
         * Write a UTF-8 string into the byte stream. Similar to the writeUTF() method, but the writeUTFBytes() method does not prefix the string with a 16-bit length word
         * @param value Character string value to be written
         * @version Egret 2.4
         * @platform Web,Native
         */
        /**
         * @language zh_CN
         * 将 UTF-8 字符串写入字节流。类似于 writeUTF() 方法，但 writeUTFBytes() 不使用 16 位长度的词为字符串添加前缀
         * @param value 要写入的字符串值
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.writeUTFBytes = function (value) {
            this._writeUint8Array(this.encodeUTF8(value));
        };
        /**
         *
         * @returns
         * @version Egret 2.4
         * @platform Web,Native
         */
        ByteArray.prototype.toString = function () {
            return "[ByteArray] length:" + this.length + ", bytesAvailable:" + this.bytesAvailable;
        };
        /**
         * @private
         * 将 Uint8Array 写入字节流
         * @param bytes 要写入的Uint8Array
         * @param validateBuffer
         */
        ByteArray.prototype._writeUint8Array = function (bytes, validateBuffer) {
            if (validateBuffer === void 0) { validateBuffer = true; }
            if (validateBuffer) {
                this.validateBuffer(this.position + bytes.length);
            }
            for (var i = 0; i < bytes.length; i++) {
                this.data.setUint8(this.position++, bytes[i]);
            }
        };
        /**
         * @param len
         * @returns
         * @version Egret 2.4
         * @platform Web,Native
         * @private
         */
        ByteArray.prototype.validate = function (len) {
            //len += this.data.byteOffset;
            if (this.data.byteLength > 0 && this._position + len <= this.data.byteLength) {
                return true;
            }
            else {
                trace('[ByteArray] 1025');
            }
        };
        /**********************/
        /*  PRIVATE METHODS   */
        /**********************/
        /**
         * @private
         * @param len
         * @param needReplace
         */
        ByteArray.prototype.validateBuffer = function (len, needReplace) {
            if (needReplace === void 0) { needReplace = false; }
            this.write_position = len > this.write_position ? len : this.write_position;
            len += this._position;
            if (this.data.byteLength < len || needReplace) {
                var tmp = new Uint8Array(new ArrayBuffer(len + this.BUFFER_EXT_SIZE));
                var length_3 = Math.min(this.data.buffer.byteLength, len + this.BUFFER_EXT_SIZE);
                tmp.set(new Uint8Array(this.data.buffer, 0, length_3));
                this.buffer = tmp.buffer;
            }
        };
        /**
         * @private
         * UTF-8 Encoding/Decoding
         */
        ByteArray.prototype.encodeUTF8 = function (str) {
            var pos = 0;
            var codePoints = this.stringToCodePoints(str);
            var outputBytes = [];
            while (codePoints.length > pos) {
                var code_point = codePoints[pos++];
                if (this.inRange(code_point, 0xD800, 0xDFFF)) {
                    this.encodertrace(code_point);
                }
                else if (this.inRange(code_point, 0x0000, 0x007f)) {
                    outputBytes.push(code_point);
                }
                else {
                    var count = void 0, offset = void 0;
                    if (this.inRange(code_point, 0x0080, 0x07FF)) {
                        count = 1;
                        offset = 0xC0;
                    }
                    else if (this.inRange(code_point, 0x0800, 0xFFFF)) {
                        count = 2;
                        offset = 0xE0;
                    }
                    else if (this.inRange(code_point, 0x10000, 0x10FFFF)) {
                        count = 3;
                        offset = 0xF0;
                    }
                    outputBytes.push(this.div(code_point, Math.pow(64, count)) + offset);
                    while (count > 0) {
                        var temp = this.div(code_point, Math.pow(64, count - 1));
                        outputBytes.push(0x80 + (temp % 64));
                        count -= 1;
                    }
                }
            }
            return new Uint8Array(outputBytes);
        };
        /**
         * @private
         *
         * @param data
         * @returns
         */
        ByteArray.prototype.decodeUTF8 = function (data) {
            var fatal = false;
            var pos = 0;
            var result = "";
            var code_point;
            var utf8_code_point = 0;
            var utf8_bytes_needed = 0;
            var utf8_bytes_seen = 0;
            var utf8_lower_boundary = 0;
            while (data.length > pos) {
                var _byte = data[pos++];
                if (_byte == this.EOF_byte) {
                    if (utf8_bytes_needed != 0) {
                        code_point = this.decodertrace(fatal);
                    }
                    else {
                        code_point = this.EOF_code_point;
                    }
                }
                else {
                    if (utf8_bytes_needed == 0) {
                        if (this.inRange(_byte, 0x00, 0x7F)) {
                            code_point = _byte;
                        }
                        else {
                            if (this.inRange(_byte, 0xC2, 0xDF)) {
                                utf8_bytes_needed = 1;
                                utf8_lower_boundary = 0x80;
                                utf8_code_point = _byte - 0xC0;
                            }
                            else if (this.inRange(_byte, 0xE0, 0xEF)) {
                                utf8_bytes_needed = 2;
                                utf8_lower_boundary = 0x800;
                                utf8_code_point = _byte - 0xE0;
                            }
                            else if (this.inRange(_byte, 0xF0, 0xF4)) {
                                utf8_bytes_needed = 3;
                                utf8_lower_boundary = 0x10000;
                                utf8_code_point = _byte - 0xF0;
                            }
                            else {
                                this.decodertrace(fatal);
                            }
                            utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed);
                            code_point = null;
                        }
                    }
                    else if (!this.inRange(_byte, 0x80, 0xBF)) {
                        utf8_code_point = 0;
                        utf8_bytes_needed = 0;
                        utf8_bytes_seen = 0;
                        utf8_lower_boundary = 0;
                        pos--;
                        code_point = this.decodertrace(fatal, _byte);
                    }
                    else {
                        utf8_bytes_seen += 1;
                        utf8_code_point = utf8_code_point + (_byte - 0x80) * Math.pow(64, utf8_bytes_needed - utf8_bytes_seen);
                        if (utf8_bytes_seen !== utf8_bytes_needed) {
                            code_point = null;
                        }
                        else {
                            var cp = utf8_code_point;
                            var lower_boundary = utf8_lower_boundary;
                            utf8_code_point = 0;
                            utf8_bytes_needed = 0;
                            utf8_bytes_seen = 0;
                            utf8_lower_boundary = 0;
                            if (this.inRange(cp, lower_boundary, 0x10FFFF) && !this.inRange(cp, 0xD800, 0xDFFF)) {
                                code_point = cp;
                            }
                            else {
                                code_point = this.decodertrace(fatal, _byte);
                            }
                        }
                    }
                }
                //Decode string
                if (code_point !== null && code_point !== this.EOF_code_point) {
                    if (code_point <= 0xFFFF) {
                        if (code_point > 0)
                            result += String.fromCharCode(code_point);
                    }
                    else {
                        code_point -= 0x10000;
                        result += String.fromCharCode(0xD800 + ((code_point >> 10) & 0x3ff));
                        result += String.fromCharCode(0xDC00 + (code_point & 0x3ff));
                    }
                }
            }
            return result;
        };
        /**
         * @private
         *
         * @param code_point
         */
        ByteArray.prototype.encodertrace = function (code_point) {
            trace('[ByteArray]1026', code_point);
        };
        /**
         * @private
         *
         * @param fatal
         * @param opt_code_point
         * @returns
         */
        ByteArray.prototype.decodertrace = function (fatal, opt_code_point) {
            if (fatal) {
                trace('[ByteArray]1027');
            }
            return opt_code_point || 0xFFFD;
        };
        /**
         * @private
         *
         * @param a
         * @param min
         * @param max
         */
        ByteArray.prototype.inRange = function (a, min, max) {
            return min <= a && a <= max;
        };
        /**
         * @private
         *
         * @param n
         * @param d
         */
        ByteArray.prototype.div = function (n, d) {
            return Math.floor(n / d);
        };
        /**
         * @private
         *
         * @param string
         */
        ByteArray.prototype.stringToCodePoints = function (string) {
            /** @type {Array.<number>} */
            var cps = [];
            // Based on http://www.w3.org/TR/WebIDL/#idl-DOMString
            var i = 0, n = string.length;
            while (i < string.length) {
                var c = string.charCodeAt(i);
                if (!this.inRange(c, 0xD800, 0xDFFF)) {
                    cps.push(c);
                }
                else if (this.inRange(c, 0xDC00, 0xDFFF)) {
                    cps.push(0xFFFD);
                }
                else {
                    if (i == n - 1) {
                        cps.push(0xFFFD);
                    }
                    else {
                        var d = string.charCodeAt(i + 1);
                        if (this.inRange(d, 0xDC00, 0xDFFF)) {
                            var a = c & 0x3FF;
                            var b = d & 0x3FF;
                            i += 1;
                            cps.push(0x10000 + (a << 10) + b);
                        }
                        else {
                            cps.push(0xFFFD);
                        }
                    }
                }
                i += 1;
            }
            return cps;
        };
        /**
         * @private
         */
        ByteArray.SIZE_OF_BOOLEAN = 1;
        /**
         * @private
         */
        ByteArray.SIZE_OF_INT8 = 1;
        /**
         * @private
         */
        ByteArray.SIZE_OF_INT16 = 2;
        /**
         * @private
         */
        ByteArray.SIZE_OF_INT32 = 4;
        /**
         * @private
         */
        ByteArray.SIZE_OF_UINT8 = 1;
        /**
         * @private
         */
        ByteArray.SIZE_OF_UINT16 = 2;
        /**
         * @private
         */
        ByteArray.SIZE_OF_UINT32 = 4;
        /**
         * @private
         */
        ByteArray.SIZE_OF_FLOAT32 = 4;
        /**
         * @private
         */
        ByteArray.SIZE_OF_FLOAT64 = 8;
        return ByteArray;
    }());
    d5.ByteArray = ByteArray;
    __reflect(ByteArray.prototype, "d5.ByteArray");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5Text = (function (_super) {
        __extends(D5Text, _super);
        function D5Text() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        D5Text.prototype.clone = function () {
            var newone = new D5Text();
            newone.init.apply(newone, this._initArgs);
            newone.setSize(this.width, this.height);
            return newone;
        };
        Object.defineProperty(D5Text.prototype, "text", {
            get: function () {
                return this._text.text;
            },
            set: function (v) {
                this._text.text = v;
                this.align(this._conf);
                //this._text.style = this._textStyle;
            },
            enumerable: true,
            configurable: true
        });
        /**
         *
         * @param args 数组，第0个元素为配置信息，格式为{fontColor:文字颜色,textValue:文字内容,fontFamily:字体,fontSize:字号,bold:提供bold或者normal，是否加粗，width:宽度,wrapType：是否换行，1表示换行0表示单行}
         */
        D5Text.prototype.init = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            _super.prototype.init.apply(this, args);
            var conf = args[0];
            this._textId = conf.textID;
            var family = conf.fontFamily;
            this._conf = conf;
            this._textStyle = new PIXI.TextStyle({
                fontFamily: family == '' ? 'Arial' : [family],
                fontSize: conf.fontSize,
                //fontStyle: 'italic',
                fontWeight: conf.bold ? 'bold' : 'normal',
                fill: conf.fontColor,
                //stroke: { color: '#4a1850', width: 5, join: 'round' },
                /*
                dropShadow: {
                color: '#000000',
                blur: 4,
                angle: Math.PI / 6,
                distance: 6,
                },
                */
                wordWrap: conf.wrapType == 1,
                breakWords: conf.wrapType == 1,
                wordWrapWidth: conf.width,
            });
            var style = this._textStyle;
            this._text = new PIXI.Text({
                text: conf.textValue,
                style: style,
            });
            this.align(conf);
            this._text.y = Math.floor(conf.fontSize * (conf.fontSize > 32 ? .1 : .2)); // AS3适配
            this._monitor.addChild(this._text);
        };
        D5Text.prototype.align = function (conf) {
            switch (conf.alignType) {
                case 1:
                    this._text.x = (conf.width - this._text.width) >> 1;
                    break;
                case 2:
                    this._text.x = conf.width - this._text.width;
                    break;
            }
        };
        Object.defineProperty(D5Text.prototype, "width", {
            get: function () {
                return this._text.width;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5Text.prototype, "height", {
            get: function () {
                return this._text.height;
            },
            enumerable: true,
            configurable: true
        });
        return D5Text;
    }(d5.D5Component));
    d5.D5Text = D5Text;
    __reflect(D5Text.prototype, "d5.D5Text");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5VBox = (function (_super) {
        __extends(D5VBox, _super);
        function D5VBox() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Draws the visual ui of the component, in this case, laying out the sub components.
         */
        D5VBox.prototype.draw = function () {
            var _w = 0;
            var _h = 0;
            var ypos = 0;
            var i = 0;
            for (i = 0; i < this.numChildren; i++) {
                var child = this.getChildAt(i);
                child.y = ypos;
                ypos += child.d5component ? child.d5component.height : child.height;
                ypos += this._padding;
                _w = Math.max(_w, child.width);
                _h = ypos;
            }
        };
        return D5VBox;
    }(d5.D5HBox));
    d5.D5VBox = D5VBox;
    __reflect(D5VBox.prototype, "d5.D5VBox");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5FlyBox = (function (_super) {
        __extends(D5FlyBox, _super);
        function D5FlyBox() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.maxWidth = 200;
            return _this;
        }
        /**
         * Draws the visual ui of the component, in this case, laying out the sub components.
         */
        D5FlyBox.prototype.draw = function () {
            var _w = 0;
            var _h = 0;
            var ypos = 0;
            var xpos = 0;
            var i = 0;
            for (i = 0; i < this.numChildren; i++) {
                var child = this.getChildAt(i);
                child.x = xpos;
                child.y = ypos;
                xpos += child.d5component ? child.d5component.width : child.width;
                xpos += this._padding;
                _w = xpos;
                _h = Math.max(_h, child.d5component ? child.d5component.height : child.height);
                if (_w > this.maxWidth) {
                    xpos = 0;
                    ypos += _h;
                    ypos += this._padding;
                    _h = 0;
                }
            }
        };
        return D5FlyBox;
    }(d5.D5HBox));
    d5.D5FlyBox = D5FlyBox;
    __reflect(D5FlyBox.prototype, "d5.D5FlyBox");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var D5HoverText = (function (_super) {
        __extends(D5HoverText, _super);
        function D5HoverText(text, color, size, leftPadding) {
            if (text === void 0) { text = ''; }
            if (color === void 0) { color = 0xffffff; }
            if (size === void 0) { size = 14; }
            if (leftPadding === void 0) { leftPadding = 5; }
            var _this = _super.call(this) || this;
            /**
             * 鼠标经过颜色
             */
            _this._hoverColor = 0;
            _this._bg = new PIXI.Graphics();
            _this._fontColor = color;
            _this._fontSize = size;
            _this._leftPadding = leftPadding;
            _this._bgRound = 5;
            _this._monitor.addChild(_this._bg);
            _this.text = text;
            _this.setupListener();
            return _this;
        }
        D5HoverText.prototype.onClick = function (call, thisobj) {
            this._onclick = call;
            this._thisobj = thisobj;
        };
        Object.defineProperty(D5HoverText.prototype, "bgRound", {
            set: function (v) {
                this._bgRound = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5HoverText.prototype, "fontColor", {
            set: function (v) {
                this._fontColor = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5HoverText.prototype, "fontSize", {
            set: function (v) {
                this._fontSize = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5HoverText.prototype, "hoverColor", {
            set: function (v) {
                this._hoverColor = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5HoverText.prototype, "hoverAlpha", {
            set: function (v) {
                this._hoverAlpha = v;
            },
            enumerable: true,
            configurable: true
        });
        D5HoverText.prototype.autoSize = function () {
            this.setSize(this._leftPadding * 2 + this._text.width, this._leftPadding * 2 + this._text.height);
        };
        D5HoverText.prototype.autoWidth = function () {
            this.setSize(this._leftPadding * 2 + this._text.width, this.realHeight);
        };
        D5HoverText.prototype.setSize = function (w, h) {
            _super.prototype.setSize.call(this, w, h);
            this._monitor.hitArea = new PIXI.Polygon([0, 0, w, 0, w, h, 0, h]);
            this._text.y = Math.floor((h - this._text.height) * .5);
        };
        Object.defineProperty(D5HoverText.prototype, "text", {
            set: function (v) {
                if (this._text)
                    this._monitor.removeChild(this._text);
                this._text = new PIXI.Text({ text: v, style: { fill: this._fontColor, fontSize: this._fontSize } });
                this._text.x = this._leftPadding;
                this._monitor.addChild(this._text);
            },
            enumerable: true,
            configurable: true
        });
        D5HoverText.prototype.updateStyle = function () {
            this.text = this._text.text;
        };
        D5HoverText.prototype.setupListener = function () {
            this.touchEnable = true;
            var that = this;
            var onOver = function (e) {
                that.hover = true;
            };
            var onOut = function (e) {
                that.hover = false;
            };
            var onTap = function (e) {
                if (that._onclick)
                    that._onclick.apply(that._thisobj, [that]);
            };
            this.addEventListener(d5.TouchEvent.TOUCH_OVER, onOver, "pointer");
            this.addEventListener(d5.TouchEvent.TOUCH_OUT, onOut);
            this.addEventListener(d5.TouchEvent.TOUCH_MOVEOUT, onOut);
            this.addEventListener(d5.TouchEvent.TOUCH_TAP, onTap);
        };
        D5HoverText.prototype.remove = function () {
            _super.prototype.remove.call(this);
            this.removeEventListener(d5.TouchEvent.TOUCH_OVER);
            this.removeEventListener(d5.TouchEvent.TOUCH_OUT);
            this.removeEventListener(d5.TouchEvent.TOUCH_MOVEOUT);
            this.removeEventListener(d5.TouchEvent.TOUCH_TAP);
        };
        D5HoverText.prototype.setHover = function (color, alpha) {
            if (alpha === void 0) { alpha = 1; }
            this._hoverColor = color;
            this._hoverAlpha = alpha;
        };
        Object.defineProperty(D5HoverText.prototype, "hover", {
            set: function (v) {
                if (v) {
                    if (D5HoverText.lastHover)
                        D5HoverText.lastHover.hover = false;
                    D5HoverText.lastHover = this;
                    if (this._bgRound == 0) {
                        this._bg.rect(0, 0, this.realWidth, this.realHeight);
                    }
                    else {
                        this._bg.roundRect(0, 0, this.realWidth, this.realHeight, this._bgRound);
                    }
                    this._bg.fill({ color: this._hoverColor, alpha: this._hoverAlpha });
                }
                else {
                    D5HoverText.lastHover = null;
                    this._bg.clear();
                }
            },
            enumerable: true,
            configurable: true
        });
        return D5HoverText;
    }(d5.D5Component));
    d5.D5HoverText = D5HoverText;
    __reflect(D5HoverText.prototype, "d5.D5HoverText");
    var D5List = (function (_super) {
        __extends(D5List, _super);
        function D5List(content_padding) {
            if (content_padding === void 0) { content_padding = 5; }
            var _this = _super.call(this) || this;
            _this._blockW = 120;
            _this._blockH = 32;
            _this._textColor = 0xffffff;
            _this._hoverColor = 0x8ec7;
            _this._hoverAlpha = 1;
            _this._fontSize = 12;
            _this._bgColor = 0x333333;
            _this._bgAlpha = 1;
            _this._bgLine = 1;
            _this._bgLineColor = 0x666666;
            _this._bgRound = 5;
            _this._leftPadding = 5;
            _this._maxWidth = 0;
            _this._list = [];
            _this._content = new d5.D5VBox;
            _this._content_padding = content_padding;
            _this._content.padding = content_padding;
            _this._content.setPosition(content_padding, content_padding);
            _this._background = new PIXI.Graphics;
            _this._monitor.addChild(_this._background);
            _this.addChild(_this._content);
            return _this;
        }
        Object.defineProperty(D5List.prototype, "padding", {
            set: function (v) {
                this._content.padding = v;
            },
            enumerable: true,
            configurable: true
        });
        D5List.prototype.dispose = function () {
            if (this._waitTime > 0)
                clearTimeout(this._waitTime);
            if (!this._list)
                return;
            for (var i = this._list.length - 1; i >= 0; i--) {
                if (this._list[i] == "")
                    continue;
                var text = this._list[i];
                text.remove();
            }
            this._content.remove();
            this._list = null;
            this.remove();
        };
        D5List.prototype.onClick = function (target) {
            this.dispathEvent(d5.Event.SELECT, target.extdata);
        };
        D5List.prototype.addItem = function (label, data) {
            if (data === void 0) { data = null; }
            var lab;
            if (label != "") {
                lab = new D5HoverText(label, this._textColor, this._fontSize, this._leftPadding);
                lab.setSize(this._blockW, this._blockH);
                lab.autoWidth();
                if (lab.width > this._maxWidth) {
                    this._maxWidth = lab.width;
                }
                lab.setHover(this._hoverColor, this._hoverAlpha);
                lab.onClick(this.onClick, this);
                lab.extdata = data;
                this._list.push(lab);
            }
            else {
                this._list.push("");
            }
            this.asyncDraw();
            return lab;
        };
        D5List.prototype.setBackground = function (color, alpha, line_color, line_width, round) {
            if (alpha === void 0) { alpha = 1; }
            if (line_color === void 0) { line_color = 0x666666; }
            if (line_width === void 0) { line_width = 0; }
            if (round === void 0) { round = 5; }
            this._bgColor = color;
            this._bgAlpha = alpha;
            this._bgLine = line_width;
            this._bgRound = round;
            this._bgLineColor = line_color;
        };
        Object.defineProperty(D5List.prototype, "leftPadding", {
            set: function (val) {
                this._leftPadding = val;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * 设置列表样式
         *
         * @param	blockW		每个区块的宽度
         * @param	blockH		每个区块的高度
         * @param	textColor	字体颜色
         * @param	hoverColor	鼠标经过颜色
         * @param	hoverAlpha	鼠标经过透明度
         * @param	textSize	字体大小
         */
        D5List.prototype.setFormat = function (blockW, blockH, textColor, hoverColor, hoverAlpha, textSize) {
            if (hoverAlpha === void 0) { hoverAlpha = 1.0; }
            if (textSize === void 0) { textSize = 12; }
            this._blockW = blockW;
            this._blockH = blockH;
            this._textColor = textColor;
            this._hoverColor = hoverColor;
            this._hoverAlpha = hoverAlpha;
            this._fontSize = textSize;
            for (var i = 0, j = this._list.length; i < j; i++) {
                var text = this._list[i];
                text.fontSize = textSize;
                text.fontColor = textColor;
                text.setHover(this._hoverColor, this._hoverAlpha);
                text.updateStyle();
            }
            this.asyncDraw();
        };
        Object.defineProperty(D5List.prototype, "blockW", {
            get: function () {
                return this._blockW;
            },
            set: function (v) {
                this._blockW = v;
                this.asyncDraw();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5List.prototype, "blockH", {
            get: function () {
                return this._blockH;
            },
            set: function (v) {
                this._blockH = v;
                this.asyncDraw();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(D5List.prototype, "count", {
            get: function () {
                return this._list.length;
            },
            enumerable: true,
            configurable: true
        });
        D5List.prototype.draw = function () {
            this._content.removeChildren();
            this._background.clear();
            var j = this._list.length;
            var p = this._content.padding;
            var offset = 0;
            var linePos = [];
            for (var i = 0; i < j; i++) {
                if (this._list[i] == "") {
                    linePos.push(offset + Math.floor(p * .5));
                }
                else {
                    var lab = this._list[i];
                    lab.setSize(this._maxWidth, this._blockH);
                    this._content.addChild(lab);
                    offset += this._blockH + p;
                }
            }
            this._blockW = this._maxWidth;
            if (this._bgRound <= 0 || isNaN(this._bgRound)) {
                this._background.rect(0, 0, this._content.x + this._blockW + this._content_padding, this._content_padding * 2 + offset - (j > 0 ? p : 0));
            }
            else {
                this._background.roundRect(0, 0, this._content.x + this._blockW + this._content_padding, this._content_padding * 2 + offset - (j > 0 ? p : 0), this._bgRound);
            }
            this._background.fill({ color: this._bgColor, alpha: this._bgAlpha });
            if (this._bgLine > 0) {
                this._background.stroke({ width: this._bgLine, color: this._bgLineColor });
                for (var i = 0, j_1 = linePos.length; i < j_1; i++) {
                    this._background.moveTo(this._content.x, linePos[i]);
                    this._background.lineTo(this._content.x + this._blockW, linePos[i]);
                }
                this._background.stroke({ width: this._bgLine, color: this._bgLineColor });
            }
            this.realWidth = this._background.width;
            this.realHeight = this._background.height;
        };
        return D5List;
    }(d5.D5Component));
    d5.D5List = D5List;
    __reflect(D5List.prototype, "d5.D5List");
})(d5 || (d5 = {}));
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
var d5;
(function (d5) {
    var rectanglePool = [];
    /**
     * A Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its
     * width and its height.<br/>
     * The x, y, width, and height properties of the Rectangle class are independent of each other; changing the value of
     * one property has no effect on the others. However, the right and bottom properties are integrally related to those
     * four properties. For example, if you change the value of the right property, the value of the width property changes;
     * if you change the bottom property, the value of the height property changes.
     * @version Egret 2.4
     * @platform Web,Native
     * @includeExample egret/geom/Rectangle.ts
     * @language en_US
     */
    /**
     * Rectangle 对象是按其位置（由它左上角的点 (x, y) 确定）以及宽度和高度定义的区域。<br/>
     * Rectangle 类的 x、y、width 和 height 属性相互独立；更改一个属性的值不会影响其他属性。
     * 但是，right 和 bottom 属性与这四个属性是整体相关的。例如，如果更改 right 属性的值，则 width
     * 属性的值将发生变化；如果更改 bottom 属性，则 height 属性的值将发生变化。
     * @version Egret 2.4
     * @platform Web,Native
     * @includeExample egret/geom/Rectangle.ts
     * @language zh_CN
     */
    var Rectangle = (function () {
        /**
         * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified
         * width and height parameters.
         * @param x The x coordinate of the top-left corner of the rectangle.
         * @param y The y coordinate of the top-left corner of the rectangle.
         * @param width The width of the rectangle, in pixels.
         * @param height The height of the rectangle, in pixels.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 创建一个新 Rectangle 对象，其左上角由 x 和 y 参数指定，并具有指定的 width 和 height 参数。
         * @param x 矩形左上角的 x 坐标。
         * @param y 矩形左上角的 y 坐标。
         * @param width 矩形的宽度（以像素为单位）。
         * @param height 矩形的高度（以像素为单位）。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        function Rectangle(x, y, width, height) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (width === void 0) { width = 0; }
            if (height === void 0) { height = 0; }
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
        /**
         * Releases a rectangle instance to the object pool.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 释放一个Rectangle实例到对象池
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.release = function (rect) {
            if (!rect) {
                return;
            }
            rectanglePool.push(rect);
        };
        /**
         * get a rectangle instance from the object pool or create a new one.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 从对象池中取出或创建一个新的Rectangle对象。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.create = function () {
            var rect = rectanglePool.pop();
            if (!rect) {
                rect = new Rectangle();
            }
            return rect;
        };
        Object.defineProperty(Rectangle.prototype, "right", {
            /**
             * The sum of the x and width properties.
             * @version Egret 2.4
             * @platform Web,Native
             * @language en_US
             */
            /**
             * x 和 width 属性的和。
             * @version Egret 2.4
             * @platform Web,Native
             * @language zh_CN
             */
            get: function () {
                return this.x + this.width;
            },
            set: function (value) {
                this.width = value - this.x;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Rectangle.prototype, "bottom", {
            /**
             * The sum of the y and height properties.
             * @version Egret 2.4
             * @platform Web,Native
             * @language en_US
             */
            /**
             * y 和 height 属性的和。
             * @version Egret 2.4
             * @platform Web,Native
             * @language zh_CN
             */
            get: function () {
                return this.y + this.height;
            },
            set: function (value) {
                this.height = value - this.y;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Rectangle.prototype, "left", {
            /**
             * The x coordinate of the top-left corner of the rectangle. Changing the left property of a Rectangle object has
             * no effect on the y and height properties. However it does affect the width property, whereas changing the x value
             * does not affect the width property.
             * The value of the left property is equal to the value of the x property.
             * @version Egret 2.4
             * @platform Web,Native
             * @language en_US
             */
            /**
             * 矩形左上角的 x 坐标。更改 Rectangle 对象的 left 属性对 y 和 height 属性没有影响。但是，它会影响 width 属性，而更改 x 值不会影响 width 属性。
             * left 属性的值等于 x 属性的值。
             * @version Egret 2.4
             * @platform Web,Native
             * @language zh_CN
             */
            get: function () {
                return this.x;
            },
            set: function (value) {
                this.width += this.x - value;
                this.x = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Rectangle.prototype, "top", {
            /**
             * The y coordinate of the top-left corner of the rectangle. Changing the top property of a Rectangle object has
             * no effect on the x and width properties. However it does affect the height property, whereas changing the y
             * value does not affect the height property.<br/>
             * The value of the top property is equal to the value of the y property.
             * @version Egret 2.4
             * @platform Web,Native
             * @language en_US
             */
            /**
             * 矩形左上角的 y 坐标。更改 Rectangle 对象的 top 属性对 x 和 width 属性没有影响。但是，它会影响 height 属性，而更改 y 值不会影响 height 属性。<br/>
             * top 属性的值等于 y 属性的值。
             * @version Egret 2.4
             * @platform Web,Native
             * @language zh_CN
             */
            get: function () {
                return this.y;
            },
            set: function (value) {
                this.height += this.y - value;
                this.y = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Rectangle.prototype, "topLeft", {
            /**
             * The location of the Rectangle object's top-left corner, determined by the x and y coordinates of the point.
             * @version Egret 2.4
             * @platform Web,Native
             * @language en_US
             */
            /**
             * 由该点的 x 和 y 坐标确定的 Rectangle 对象左上角的位置。
             * @version Egret 2.4
             * @platform Web,Native
             * @language zh_CN
             */
            get: function () {
                return new d5.Point(this.left, this.top);
            },
            set: function (value) {
                this.top = value.y;
                this.left = value.x;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Rectangle.prototype, "bottomRight", {
            /**
             * The location of the Rectangle object's bottom-right corner, determined by the values of the right and bottom properties.
             * @version Egret 2.4
             * @platform Web,Native
             * @language en_US
             */
            /**
             * 由 right 和 bottom 属性的值确定的 Rectangle 对象的右下角的位置。
             * @version Egret 2.4
             * @platform Web,Native
             * @language zh_CN
             */
            get: function () {
                return new d5.Point(this.right, this.bottom);
            },
            set: function (value) {
                this.bottom = value.y;
                this.right = value.x;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Copies all of rectangle data from the source Rectangle object into the calling Rectangle object.
         * @param sourceRect The Rectangle object from which to copy the data.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将源 Rectangle 对象中的所有矩形数据复制到调用方 Rectangle 对象中。
         * @param sourceRect 要从中复制数据的 Rectangle 对象。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.copyFrom = function (sourceRect) {
            this.x = sourceRect.x;
            this.y = sourceRect.y;
            this.width = sourceRect.width;
            this.height = sourceRect.height;
            return this;
        };
        /**
         * Sets the members of Rectangle to the specified values
         * @param x The x coordinate of the top-left corner of the rectangle.
         * @param y The y coordinate of the top-left corner of the rectangle.
         * @param width The width of the rectangle, in pixels.
         * @param height The height of the rectangle, in pixels.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将 Rectangle 的成员设置为指定值
         * @param x 矩形左上角的 x 坐标。
         * @param y 矩形左上角的 y 坐标。
         * @param width 矩形的宽度（以像素为单位）。
         * @param height 矩形的高度（以像素为单位）。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.setTo = function (x, y, width, height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            return this;
        };
        /**
         * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object.
         * @param x The x coordinate (horizontal position) of the point.
         * @param y The y coordinate (vertical position) of the point.
         * @returns A value of true if the Rectangle object contains the specified point; otherwise false.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 确定由此 Rectangle 对象定义的矩形区域内是否包含指定的点。
         * @param x 检测点的x轴
         * @param y 检测点的y轴
         * @returns 如果检测点位于矩形内，返回true，否则，返回false
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.contains = function (x, y) {
            return this.x <= x &&
                this.x + this.width >= x &&
                this.y <= y &&
                this.y + this.height >= y;
        };
        /**
         * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns
         * the area of intersection as a Rectangle object. If the rectangles do not intersect, this method returns an empty
         * Rectangle object with its properties set to 0.
         * @param toIntersect The Rectangle object to compare against to see if it intersects with this Rectangle object.
         * @returns A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method
         * returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 如果在 toIntersect 参数中指定的 Rectangle 对象与此 Rectangle 对象相交，则返回交集区域作为 Rectangle 对象。如果矩形不相交，
         * 则此方法返回一个空的 Rectangle 对象，其属性设置为 0。
         * @param toIntersect 要对照比较以查看其是否与此 Rectangle 对象相交的 Rectangle 对象。
         * @returns 等于交集区域的 Rectangle 对象。如果该矩形不相交，则此方法返回一个空的 Rectangle 对象；即，其 x、y、width 和
         * height 属性均设置为 0 的矩形。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.intersection = function (toIntersect) {
            return this.clone().$intersectInPlace(toIntersect);
        };
        /**
         * Increases the size of the Rectangle object by the specified amounts, in pixels.
         * The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
         * @param dx The value to be added to the left and the right of the Rectangle object.
         * @param dy The value to be added to the top and the bottom of the Rectangle.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 按指定量增加 Rectangle 对象的大小（以像素为单位）
         * 保持 Rectangle 对象的中心点不变，使用 dx 值横向增加它的大小，使用 dy 值纵向增加它的大小。
         * @param dx Rectangle 对象横向增加的值。
         * @param dy Rectangle 对象纵向增加的值。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.inflate = function (dx, dy) {
            this.x -= dx;
            this.width += 2 * dx;
            this.y -= dy;
            this.height += 2 * dy;
        };
        /**
         * @private
         */
        Rectangle.prototype.$intersectInPlace = function (clipRect) {
            var x0 = this.x;
            var y0 = this.y;
            var x1 = clipRect.x;
            var y1 = clipRect.y;
            var l = Math.max(x0, x1);
            var r = Math.min(x0 + this.width, x1 + clipRect.width);
            if (l <= r) {
                var t = Math.max(y0, y1);
                var b = Math.min(y0 + this.height, y1 + clipRect.height);
                if (t <= b) {
                    this.setTo(l, t, r - l, b - t);
                    return this;
                }
            }
            this.setEmpty();
            return this;
        };
        /**
         * Determines whether the object specified in the toIntersect parameter intersects with this Rectangle object.
         * This method checks the x, y, width, and height properties of the specified Rectangle object to see if it
         * intersects with this Rectangle object.
         * @param toIntersect The Rectangle object to compare against this Rectangle object.
         * @returns A value of true if the specified object intersects with this Rectangle object; otherwise false.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 确定在 toIntersect 参数中指定的对象是否与此 Rectangle 对象相交。此方法检查指定的 Rectangle
         * 对象的 x、y、width 和 height 属性，以查看它是否与此 Rectangle 对象相交。
         * @param toIntersect 要与此 Rectangle 对象比较的 Rectangle 对象。
         * @returns 如果两个矩形相交，返回true，否则返回false
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.intersects = function (toIntersect) {
            return Math.max(this.x, toIntersect.x) <= Math.min(this.right, toIntersect.right)
                && Math.max(this.y, toIntersect.y) <= Math.min(this.bottom, toIntersect.bottom);
        };
        /**
         * Determines whether or not this Rectangle object is empty.
         * @returns A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 确定此 Rectangle 对象是否为空。
         * @returns 如果 Rectangle 对象的宽度或高度小于等于 0，则返回 true 值，否则返回 false。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.isEmpty = function () {
            return this.width <= 0 || this.height <= 0;
        };
        /**
         * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将 Rectangle 对象的所有属性设置为 0。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.setEmpty = function () {
            this.x = 0;
            this.y = 0;
            this.width = 0;
            this.height = 0;
        };
        /**
         * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
         * @returns A new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 返回一个新的 Rectangle 对象，其 x、y、width 和 height 属性的值与原始 Rectangle 对象的对应值相同。
         * @returns 新的 Rectangle 对象，其 x、y、width 和 height 属性的值与原始 Rectangle 对象的对应值相同。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.clone = function () {
            return new Rectangle(this.x, this.y, this.width, this.height);
        };
        /**
         * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object.
         * This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter.
         * @param point The point, as represented by its x and y coordinates.
         * @returns A value of true if the Rectangle object contains the specified point; otherwise false.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 确定由此 Rectangle 对象定义的矩形区域内是否包含指定的点。
         * 此方法与 Rectangle.contains() 方法类似，只不过它采用 Point 对象作为参数。
         * @param point 包含点对象
         * @returns 如果包含，返回true，否则返回false
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.containsPoint = function (point) {
            if (this.x <= point.x
                && this.x + this.width >= point.x
                && this.y <= point.y
                && this.y + this.height >= point.y) {
                return true;
            }
            return false;
        };
        /**
         * Determines whether the Rectangle object specified by the rect parameter is contained within this Rectangle object.
         * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
         * @param rect The Rectangle object being checked.
         * @returns A value of true if the Rectangle object that you specify is contained by this Rectangle object; otherwise false.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 确定此 Rectangle 对象内是否包含由 rect 参数指定的 Rectangle 对象。
         * 如果一个 Rectangle 对象完全在另一个 Rectangle 的边界内，我们说第二个 Rectangle 包含第一个 Rectangle。
         * @param rect 所检查的 Rectangle 对象
         * @returns 如果此 Rectangle 对象包含您指定的 Rectangle 对象，则返回 true 值，否则返回 false。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.containsRect = function (rect) {
            var r1 = rect.x + rect.width;
            var b1 = rect.y + rect.height;
            var r2 = this.x + this.width;
            var b2 = this.y + this.height;
            return (rect.x >= this.x) && (rect.x < r2) && (rect.y >= this.y) && (rect.y < b2) && (r1 > this.x) && (r1 <= r2) && (b1 > this.y) && (b1 <= b2);
        };
        /**
         * Determines whether the object specified in the toCompare parameter is equal to this Rectangle object.
         * This method compares the x, y, width, and height properties of an object against the same properties of this Rectangle object.
         * @param The rectangle to compare to this Rectangle object.
         * @returns A value of true if the object has exactly the same values for the x, y, width, and height properties as this Rectangle object; otherwise false.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 确定在 toCompare 参数中指定的对象是否等于此 Rectangle 对象。
         * 此方法将某个对象的 x、y、width 和 height 属性与此 Rectangle 对象所对应的相同属性进行比较。
         * @param toCompare 要与此 Rectangle 对象进行比较的矩形。
         * @returns 如果对象具有与此 Rectangle 对象完全相同的 x、y、width 和 height 属性值，则返回 true 值，否则返回 false。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.equals = function (toCompare) {
            if (this === toCompare) {
                return true;
            }
            return this.x === toCompare.x && this.y === toCompare.y
                && this.width === toCompare.width && this.height === toCompare.height;
        };
        /**
         * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter.
         * @param point 此 Point 对象的 x 属性用于增加 Rectangle 对象的水平尺寸。y 属性用于增加 Rectangle 对象的垂直尺寸。
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 增加 Rectangle 对象的大小。此方法与 Rectangle.inflate() 方法类似，只不过它采用 Point 对象作为参数。
         * @param point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object.
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.inflatePoint = function (point) {
            this.inflate(point.x, point.y);
        };
        /**
         * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
         * @param dx Moves the x value of the Rectangle object by this amount.
         * @param dy Moves the y value of the Rectangle object by this amount.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 按指定量调整 Rectangle 对象的位置（由其左上角确定）。
         * @param dx 将 Rectangle 对象的 x 值移动此数量。
         * @param dy 将 Rectangle 对象的 t 值移动此数量。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.offset = function (dx, dy) {
            this.x += dx;
            this.y += dy;
        };
        /**
         * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter.
         * @param point A Point object to use to offset this Rectangle object.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 将 Point 对象用作参数来调整 Rectangle 对象的位置。此方法与 Rectangle.offset() 方法类似，只不过它采用 Point 对象作为参数。
         * @param point 要用于偏移此 Rectangle 对象的 Point 对象。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.offsetPoint = function (point) {
            this.offset(point.x, point.y);
        };
        /**
         * Builds and returns a string that lists the horizontal and vertical positions and the width and height of the Rectangle object.
         * @returns A string listing the value of each of the following properties of the Rectangle object: x, y, width, and height.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 生成并返回一个字符串，该字符串列出 Rectangle 对象的水平位置和垂直位置以及高度和宽度。
         * @returns 一个字符串，它列出了 Rectangle 对象的下列各个属性的值：x、y、width 和 height。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.toString = function () {
            return "(x=" + this.x + ", y=" + this.y + ", width=" + this.width + ", height=" + this.height + ")";
        };
        /**
         * Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles.
         * @param toUnion A Rectangle object to add to this Rectangle object.
         * @returns A new Rectangle object that is the union of the two rectangles.
         * @version Egret 2.4
         * @platform Web,Native
         * @language en_US
         */
        /**
         * 通过填充两个矩形之间的水平和垂直空间，将这两个矩形组合在一起以创建一个新的 Rectangle 对象。
         * @param toUnion 要添加到此 Rectangle 对象的 Rectangle 对象。
         * @returns 充当两个矩形的联合的新 Rectangle 对象。
         * @version Egret 2.4
         * @platform Web,Native
         * @language zh_CN
         */
        Rectangle.prototype.union = function (toUnion) {
            var result = this.clone();
            if (toUnion.isEmpty()) {
                return result;
            }
            if (result.isEmpty()) {
                result.copyFrom(toUnion);
                return result;
            }
            var l = Math.min(result.x, toUnion.x);
            var t = Math.min(result.y, toUnion.y);
            result.setTo(l, t, Math.max(result.right, toUnion.right) - l, Math.max(result.bottom, toUnion.bottom) - t);
            return result;
        };
        /**
         * @private
         */
        Rectangle.prototype.$getBaseWidth = function (angle) {
            var u = Math.abs(Math.cos(angle));
            var v = Math.abs(Math.sin(angle));
            return u * this.width + v * this.height;
        };
        /**
         * @private
         */
        Rectangle.prototype.$getBaseHeight = function (angle) {
            var u = Math.abs(Math.cos(angle));
            var v = Math.abs(Math.sin(angle));
            return v * this.width + u * this.height;
        };
        return Rectangle;
    }());
    d5.Rectangle = Rectangle;
    __reflect(Rectangle.prototype, "d5.Rectangle");
    /**
     * @private
     * 仅供框架内复用，要防止暴露引用到外部。
     */
    d5.$TempRectangle = new Rectangle();
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    /**
     * 界面模板处理
     *
     */
    var D5Template = (function () {
        function D5Template() {
            this._skin = [];
            this._map = {};
        }
        /**
         * 从组件直接初始化，用于程序开发
         * @param root 根对象
         * @param target 克隆皮肤
         */
        D5Template.prototype.fromComponent = function (root) {
            var target = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                target[_i - 1] = arguments[_i];
            }
            this._root = root;
            var off;
            off = [root.x, root.y];
            this._skin.push(root);
            root.setPosition(0, 0);
            root.parent && root.parent.removeChild(root.monitor);
            for (var i = 0, j = target.length; i < j; i++) {
                var comp = target[i];
                if (!comp || comp == root)
                    continue;
                if (off && comp.parent != root) {
                    comp.setPosition(comp.x - off[0], comp.y - off[1]);
                }
                comp.parent && comp.parent.removeChild(comp.monitor);
                this._skin.push(comp);
            }
        };
        /**
         * 获取一个克隆皮肤，并绑定到一个类
         * @param bindTarget 要绑定的类
         */
        D5Template.prototype.getInstanceBind = function (bindTarget) {
            var instance = new bindTarget();
            for (var i = 0, j = this._skin.length; i < j; i++) {
                var comp = this._skin[i];
                if (comp['clone']) {
                    var n_comp = comp.clone();
                    n_comp.setPosition(comp.x, comp.y);
                    instance.addChild(n_comp);
                    try {
                        instance[comp.name] = n_comp;
                    }
                    catch (e) {
                    }
                }
            }
            return instance;
        };
        return D5Template;
    }());
    d5.D5Template = D5Template;
    __reflect(D5Template.prototype, "d5.D5Template");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var SpineCharacter = (function (_super) {
        __extends(SpineCharacter, _super);
        function SpineCharacter(json, atlas, default_scale) {
            if (default_scale === void 0) { default_scale = 0.2; }
            var _this = _super.call(this) || this;
            _this._speakState = false;
            _this._scale = default_scale;
            _this.jsonID = D5Power.md5.hex_md5(json);
            _this.atlasID = D5Power.md5.hex_md5(atlas);
            if (PIXI.Assets.get(_this.jsonID)) {
                _this.init();
            }
            else {
                _this.loadRes(json, atlas);
            }
            return _this;
        }
        SpineCharacter.prototype.updateSpeekList = function (arr) {
            this._speakList = arr;
        };
        SpineCharacter.prototype.speak = function () {
            if (!this._speakList || this._speakState)
                return;
            var that = this;
            var count = that._speakList.length;
            that._speakState = true;
            var speak_do = function () {
                var idx = Math.floor(Math.random() * count);
                var name = that._speakList[idx];
                var entry = that._spine.state.setAnimation(1, name, false);
                entry.listener = {
                    complete: function (trackIndex, loopCount) {
                        // 攻击动画结束后回到待机状态
                        if (that._speakState) {
                            speak_do();
                        }
                        else {
                            that._spine.state.clearTrack(1);
                        }
                    }
                };
            };
            speak_do();
        };
        SpineCharacter.prototype.stopSpeak = function () {
            this._speakState = false;
            this.clearMixAnimation();
        };
        SpineCharacter.prototype.once = function (event, listener) {
            if (this._spine) {
                _super.prototype.once.call(this, event, listener);
            }
            else {
                this._once = { event: event, listener: listener };
            }
        };
        SpineCharacter.prototype.loadRes = function (json, atlas) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            PIXI.Assets.add({ alias: this.jsonID, src: json });
                            PIXI.Assets.add({ alias: this.atlasID, src: atlas });
                            return [4 /*yield*/, PIXI.Assets.load([this.jsonID, this.atlasID])];
                        case 1:
                            _a.sent();
                            this.init();
                            return [2 /*return*/];
                    }
                });
            });
        };
        SpineCharacter.prototype.hasAnimation = function (name) {
            return this._animations.indexOf(name) != -1;
        };
        SpineCharacter.prototype.playAnimation = function (name, loop, channle) {
            var _this = this;
            if (loop === void 0) { loop = true; }
            if (channle === void 0) { channle = 0; }
            var entry = this._spine.state.setAnimation(channle, name, loop);
            if (!loop) {
                entry.listener = {
                    complete: function (trackIndex, loopCount) {
                        // 攻击动画结束后回到待机状态
                        _this._spine.state.setAnimation(channle, "idle", true);
                    }
                };
            }
        };
        SpineCharacter.prototype.clearMixAnimation = function (channle) {
            if (channle === void 0) { channle = 1; }
            this._spine.state.setEmptyAnimation(channle, 0);
        };
        SpineCharacter.prototype.mixAnimation = function (name, dely, channle) {
            if (dely === void 0) { dely = 0; }
            if (channle === void 0) { channle = 1; }
            trace(name);
            return dely ? this._spine.state.addAnimation(channle, name, false) : this._spine.state.addAnimation(channle, name, dely, false);
        };
        SpineCharacter.prototype.init = function () {
            var config = PIXI.Assets.get(this.jsonID);
            var anmiations = config.animations;
            var anmi_arr = [];
            for (var k in anmiations) {
                anmi_arr.push(k);
            }
            this._animations = anmi_arr;
            trace("[SpineCharacter] supported animations " + anmi_arr);
            var spineboy = spine.Spine.from({ skeleton: this.jsonID, atlas: this.atlasID, scale: this._scale });
            spineboy.state.data.defaultMix = 0.2;
            this._monitor = spineboy;
            this._monitor.d5component = this;
            if (this._once) {
                this._monitor.once(this._once.event, this._once.listener);
                this._once = null;
            }
            this._spine = spineboy;
            this.offset = { x: config.skeleton.x, y: config.skeleton.y };
            this.setSize(config.skeleton.width, config.skeleton.height);
            this.dispathEvent(d5.Event.COMPLETE, this);
        };
        return SpineCharacter;
    }(d5.DisplayContainer));
    d5.SpineCharacter = SpineCharacter;
    __reflect(SpineCharacter.prototype, "d5.SpineCharacter");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    /**
     * 单行角色::一般用于场景元素、NPC及简单动画效果
     *
     */
    var SingleFrameCharacter = (function (_super) {
        __extends(SingleFrameCharacter, _super);
        /**
         *
         * @param skin 贴图地址
         * @param frames 贴图包含帧数，帧数决定了单帧的宽度
         * @param onReady 当加载完成后的回调函数
         */
        function SingleFrameCharacter(skin, frames, onReady) {
            if (skin === void 0) { skin = null; }
            if (frames === void 0) { frames = NaN; }
            if (onReady === void 0) { onReady = null; }
            var _this = _super.call(this) || this;
            _this._actionCache = {}; // 基于动作的缓存
            _this._onReady = onReady;
            if (skin == null && isNaN(frames)) {
            }
            else {
                _this._skin = skin;
                _this._frames = frames;
                _this.loadTexture(skin, frames);
            }
            return _this;
        }
        /**
         * 对角色进行水平方向翻转
         */
        SingleFrameCharacter.prototype.mirror = function () {
            this._monitor.scale.x < 0 ? this._monitor.scale.set(Math.abs(this._monitor.scale.x), this._monitor.scale.y) : this._monitor.scale.set(-Math.abs(this._monitor.scale.x), this._monitor.scale.y);
        };
        SingleFrameCharacter.prototype.unmirror = function () {
            this._monitor.scale.set(1, 1);
        };
        /**
         * 读取贴图
         * @param skin  贴图路径
         * @param frame 包含的帧数
         * @param action 贴图对应的动作，默认为idle
         */
        SingleFrameCharacter.prototype.loadTexture = function (skin, frames, action) {
            if (action === void 0) { action = "idle"; }
            return __awaiter(this, void 0, void 0, function () {
                var cacheKey, texture, textureWidth, textureHeight, frameWidth, frameHeight, spritesheetData, spritesheet_1, animationFrames, i, error_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 3, , 4]);
                            cacheKey = "" + action;
                            // 检查缓存中是否已存在该动作的数据
                            if (this._actionCache[cacheKey]) {
                                console.log("[SingleFrameCharacter] \u4F7F\u7528\u7F13\u5B58\u7684\u52A8\u4F5C\u6570\u636E: " + cacheKey);
                                this.setupFromCache(cacheKey, action);
                                return [2 /*return*/];
                            }
                            // 加载纹理
                            return [4 /*yield*/, PIXI.Assets.load(skin)];
                        case 1:
                            // 加载纹理
                            _a.sent();
                            texture = PIXI.Assets.get(skin);
                            // 保存纹理引用
                            this._texture = texture;
                            textureWidth = texture.width;
                            textureHeight = texture.height;
                            frameWidth = Math.floor(textureWidth / frames);
                            frameHeight = textureHeight;
                            spritesheetData = this.generateSpritesheetData(skin, frames, frameWidth, frameHeight, textureWidth, textureHeight, cacheKey);
                            spritesheet_1 = new PIXI.Spritesheet(texture, spritesheetData);
                            // 解析精灵表
                            return [4 /*yield*/, spritesheet_1.parse()];
                        case 2:
                            // 解析精灵表
                            _a.sent();
                            animationFrames = [];
                            for (i = 1; i <= frames; i++) {
                                animationFrames.push(cacheKey + "_" + i);
                            }
                            // 缓存该动作的数据
                            this._actionCache[cacheKey] = {
                                texture: texture,
                                spritesheet: spritesheet_1,
                                animationFrames: animationFrames,
                                frameWidth: frameWidth,
                                frameHeight: frameHeight,
                                frames: frames
                            };
                            // 若加载动作为待机，则设置当前动作
                            if (action == 'idle') {
                                this._currentAction = action;
                                // 保存动画帧数组
                                this._animationFrames = animationFrames;
                                this._spritesheet = spritesheet_1;
                                // 创建动画精灵
                                this._animatedSprite = new PIXI.AnimatedSprite(animationFrames.map(function (frameName) { return spritesheet_1.textures[frameName]; }));
                                // 设置动画属性
                                this._animatedSprite.animationSpeed = 0.1; // 动画速度
                                this._animatedSprite.loop = true; // 循环播放
                                this._animatedSprite.play(); // 开始播放
                                // 设置为显示器
                                this._monitor = this._animatedSprite;
                                this._monitor.d5component = this;
                                // 设置尺寸
                                this.setSize(frameWidth, frameHeight);
                                this._monitor.anchor.set(0.5, 0.9);
                                // 派发完成事件
                                if (this._onReady != null) {
                                    this._onReady(this);
                                    this._onReady = null;
                                }
                            }
                            return [3 /*break*/, 4];
                        case 3:
                            error_1 = _a.sent();
                            console.error('[SingleFrameCharacter] 加载纹理失败:', error_1);
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        SingleFrameCharacter.prototype.generateSpritesheetData = function (skin, frames, frameWidth, frameHeight, textureWidth, textureHeight, cacheKey) {
            if (cacheKey === void 0) { cacheKey = null; }
            var atlasData = { frames: {}, meta: { scale: 2 } };
            var framesData = {};
            var framesName = [];
            // 生成每一帧的数据（只有一行）
            for (var i = 0; i < frames; i++) {
                var frameName = cacheKey ? cacheKey + "_" + (i + 1) : skin + "_" + (i + 1);
                framesName.push(frameName);
                var currentX = i * frameWidth;
                framesData[frameName] = {
                    "frame": {
                        "x": currentX,
                        "y": 0,
                        "w": frameWidth,
                        "h": frameHeight
                    },
                    "spriteSourceSize": {
                        "x": 0,
                        "y": 0,
                        "w": frameWidth,
                        "h": frameHeight
                    },
                    "sourceSize": {
                        "w": frameWidth,
                        "h": frameHeight
                    }
                };
            }
            // 生成完整的精灵表配置
            atlasData.frames = framesData;
            return atlasData;
        };
        /**
         * 从缓存中设置动作数据
         * @param cacheKey 缓存键
         * @param action 动作名称
         */
        SingleFrameCharacter.prototype.setupFromCache = function (cacheKey, action) {
            var cachedData = this._actionCache[cacheKey];
            if (!cachedData) {
                console.error("[SingleFrameCharacter] \u7F13\u5B58\u6570\u636E\u4E0D\u5B58\u5728: " + cacheKey);
                return;
            }
            // 使用缓存的数据
            this._texture = cachedData.texture;
            this._spritesheet = cachedData.spritesheet;
            this._animationFrames = cachedData.animationFrames;
            this._currentAction = action;
            // 如果已存在动画精灵，重用并更新其纹理
            if (this._animatedSprite) {
                // 停止当前动画
                this._animatedSprite.stop();
                // 更新动画帧纹理
                var newTextures = cachedData.animationFrames.map(function (frameName) { return cachedData.spritesheet.textures[frameName]; });
                this._animatedSprite.textures = newTextures;
                // 重置动画到第一帧
                this._animatedSprite.gotoAndStop(0);
                // 设置动画属性
                this._animatedSprite.animationSpeed = 0.1;
                this._animatedSprite.loop = true;
                this._animatedSprite.play();
            }
            else {
                // 如果不存在动画精灵，创建新的（这种情况应该很少见）
                this._animatedSprite = new PIXI.AnimatedSprite(cachedData.animationFrames.map(function (frameName) { return cachedData.spritesheet.textures[frameName]; }));
                // 设置动画属性
                this._animatedSprite.animationSpeed = 0.1;
                this._animatedSprite.loop = true;
                this._animatedSprite.play();
                // 设置为显示器
                this._monitor = this._animatedSprite;
                this._monitor.d5component = this;
            }
            // 设置尺寸
            this.setSize(cachedData.frameWidth, cachedData.frameHeight);
        };
        SingleFrameCharacter.prototype.play = function () {
            if (this._animatedSprite) {
                this._animatedSprite.play();
            }
        };
        SingleFrameCharacter.prototype.stop = function () {
            if (this._animatedSprite) {
                this._animatedSprite.stop();
            }
        };
        Object.defineProperty(SingleFrameCharacter.prototype, "animationSpeed", {
            get: function () {
                return this._animatedSprite ? this._animatedSprite.animationSpeed : 0;
            },
            set: function (value) {
                if (this._animatedSprite) {
                    this._animatedSprite.animationSpeed = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SingleFrameCharacter.prototype, "loop", {
            get: function () {
                return this._animatedSprite ? this._animatedSprite.loop : false;
            },
            set: function (value) {
                if (this._animatedSprite) {
                    this._animatedSprite.loop = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * 加载指定动作的纹理
         * @param skin 贴图地址
         * @param frames 贴图包含帧数
         * @param action 动作名称
         * @param onReady 加载完成回调
         */
        SingleFrameCharacter.prototype.loadAction = function (skin, frames, action, onReady) {
            if (action === void 0) { action = 'idle'; }
            if (onReady === void 0) { onReady = null; }
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this._onReady = onReady;
                            this._skin = skin;
                            this._frames = frames;
                            return [4 /*yield*/, this.loadTexture(skin, frames, action)];
                        case 1:
                            _a.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * 切换到已缓存的动作
         * @param action 动作名称
         * @returns 是否切换成功
         */
        SingleFrameCharacter.prototype.switchAction = function (action) {
            var cacheKey = "" + action;
            if (!this._actionCache[cacheKey]) {
                console.warn("[SingleFrameCharacter] \u52A8\u4F5C\u4E0D\u5B58\u5728\u4E8E\u7F13\u5B58\u4E2D: " + action);
                return false;
            }
            this.setupFromCache(cacheKey, action);
            return true;
        };
        Object.defineProperty(SingleFrameCharacter.prototype, "currentAction", {
            /**
             * 获取当前动作名称
             * @returns 当前动作名称
             */
            get: function () {
                return this._currentAction || "default";
            },
            enumerable: true,
            configurable: true
        });
        /**
         * 检查动作是否已缓存
         * @param action 动作名称
         * @returns 是否已缓存
         */
        SingleFrameCharacter.prototype.hasAction = function (action) {
            if (!this._skin)
                return false;
            var cacheKey = this._skin + "_" + action;
            return !!this._actionCache[cacheKey];
        };
        /**
         * 获取所有已缓存的动作名称
         * @returns 动作名称数组
         */
        SingleFrameCharacter.prototype.getCachedActions = function () {
            if (!this._skin)
                return [];
            var actions = [];
            var prefix = this._skin + "_";
            for (var key in this._actionCache) {
                if (key.indexOf(prefix) === 0) {
                    actions.push(key.substring(prefix.length));
                }
            }
            return actions;
        };
        /**
         * 清除指定动作的缓存
         * @param action 动作名称
         */
        SingleFrameCharacter.prototype.clearActionCache = function (action) {
            if (!this._skin)
                return;
            var cacheKey = this._skin + "_" + action;
            delete this._actionCache[cacheKey];
        };
        /**
         * 清除所有动作缓存
         */
        SingleFrameCharacter.prototype.clearAllActionCache = function () {
            this._actionCache = {};
        };
        /**
         * 克隆一个新的SingleFrameCharacter实例，共用贴图素材
         * @returns 克隆的新实例
         */
        SingleFrameCharacter.prototype.clone = function () {
            // 创建新实例
            var clonedCharacter = new SingleFrameCharacter();
            // 等待原始实例加载完成后，直接设置克隆实例的属性
            // 避免重新加载贴图
            this.setupClone(clonedCharacter);
            return clonedCharacter;
        };
        /**
         * 设置克隆实例的属性，共用贴图素材
         * @param clonedCharacter 克隆的实例
         */
        SingleFrameCharacter.prototype.setupClone = function (clonedCharacter) {
            var _this = this;
            // 直接使用已保存的纹理和精灵表数据，避免重新加载
            clonedCharacter._texture = this._texture;
            clonedCharacter._spritesheet = this._spritesheet;
            clonedCharacter._animationFrames = this._animationFrames;
            clonedCharacter._actionCache = this._actionCache; // 共享动作缓存
            clonedCharacter._currentAction = this._currentAction;
            // 创建新的动画精灵，但使用相同的纹理
            var clonedAnimatedSprite = new PIXI.AnimatedSprite(this._animationFrames.map(function (frameName) { return _this._spritesheet.textures[frameName]; }));
            // 复制动画属性
            clonedAnimatedSprite.animationSpeed = this._animatedSprite.animationSpeed;
            clonedAnimatedSprite.loop = this._animatedSprite.loop;
            clonedAnimatedSprite.play(); // 开始播放
            // 设置克隆实例的显示器
            clonedCharacter._animatedSprite = clonedAnimatedSprite;
            clonedCharacter._monitor = clonedAnimatedSprite;
            clonedCharacter._monitor.d5component = clonedCharacter;
            // 设置尺寸
            clonedCharacter.setSize(this.width, this.height);
            // 派发完成事件
            clonedCharacter.dispathEvent(d5.Event.COMPLETE, clonedCharacter);
        };
        return SingleFrameCharacter;
    }(d5.DisplayContainer));
    d5.SingleFrameCharacter = SingleFrameCharacter;
    __reflect(SingleFrameCharacter.prototype, "d5.SingleFrameCharacter");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var IsoUtils = (function () {
        function IsoUtils() {
        }
        /**
         * Converts a 3D point in isometric space to a 2D screen position.
         * @arg pos the 3D point.
         */
        IsoUtils.isoToScreen = function (pos) {
            var screenX = pos.x - pos.z;
            var screenY = pos.y * this.Y_CORRECT + (pos.x + pos.z) * .5;
            return new d5.Point(screenX, screenY);
        };
        /**
         * Converts a 2D screen position to a 3D point in isometric space, assuming y = 0.
         * @arg point the 2D point.
         */
        IsoUtils.screenToIso = function (point) {
            var xpos = point.y + point.x * .5;
            var ypos = 0;
            var zpos = point.y - point.x * .5;
            return new d5.Point3D(xpos, ypos, zpos);
        };
        // a more accurate version of 1.2247...
        IsoUtils.Y_CORRECT = Math.cos(-Math.PI / 6) * Math.SQRT2;
        return IsoUtils;
    }());
    d5.IsoUtils = IsoUtils;
    __reflect(IsoUtils.prototype, "d5.IsoUtils");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    /**
     * 矢量地图数据生成器
     */
    var IsoGeneratorGraphics = (function () {
        function IsoGeneratorGraphics(r, g, b) {
            if (r === void 0) { r = 40; }
            if (g === void 0) { g = 180; }
            if (b === void 0) { b = 40; }
            this.colorVariation = 10;
            this.maxDeviation = 20;
            this.colorMap = {}; // 存储地砖颜色，用于确保相邻地砖颜色相近
            this.baseGreen = { r: r, g: g, b: b }; // 基础色
        }
        /**
         * 生成地图数据
         * @param tilesX X方向的砖块数量
         * @param tilesY Y方向的砖块数量
         * @returns 地图数据
         */
        IsoGeneratorGraphics.prototype.buildMap = function (tilesX, tilesY) {
            var fillMap = [];
            for (var y = 0; y < tilesY; y++) {
                for (var x = 0; x < tilesX; x++) {
                    fillMap.push(this.getTileColor(x, y));
                }
            }
            return fillMap;
        };
        /**
         * 生成基于位置的相近绿色
         * @param {number} gridX 地砖的网格位置X
         * @param {number} gridY 地砖的网格位置Y
         * @returns {number} 绿色的十六进制颜色值
         */
        IsoGeneratorGraphics.prototype.getTileColor = function (gridX, gridY) {
            var key = gridX + "_" + gridY;
            // 如果已经计算过这个位置的颜色，直接返回
            if (this.colorMap[key]) {
                return this.colorMap[key];
            }
            // 获取相邻地砖的颜色
            var neighbors = this.getNeighborColors(gridX, gridY);
            // 计算新颜色
            var r, g, b;
            if (neighbors.length > 0) {
                // 基于相邻地砖的颜色计算新颜色
                var avgR = 0, avgG = 0, avgB = 0;
                for (var _i = 0, neighbors_1 = neighbors; _i < neighbors_1.length; _i++) {
                    var color_1 = neighbors_1[_i];
                    avgR += (color_1 >> 16) & 0xFF;
                    avgG += (color_1 >> 8) & 0xFF;
                    avgB += color_1 & 0xFF;
                }
                avgR = Math.floor(avgR / neighbors.length);
                avgG = Math.floor(avgG / neighbors.length);
                avgB = Math.floor(avgB / neighbors.length);
                // 混合相邻颜色和基准色，确保不会偏离太远
                var blendFactor = 0.3; // 30%基准色，70%相邻色
                r = Math.floor(avgR * (1 - blendFactor) + this.baseGreen.r * blendFactor);
                g = Math.floor(avgG * (1 - blendFactor) + this.baseGreen.g * blendFactor);
                b = Math.floor(avgB * (1 - blendFactor) + this.baseGreen.b * blendFactor);
                // 在混合后的颜色基础上添加小的随机变化
                r = this.clampToBaseColor(r + Math.floor(Math.random() * this.colorVariation * 2) - this.colorVariation, this.baseGreen.r);
                g = this.clampToBaseColor(g + Math.floor(Math.random() * this.colorVariation * 2) - this.colorVariation, this.baseGreen.g);
                b = this.clampToBaseColor(b + Math.floor(Math.random() * this.colorVariation * 2) - this.colorVariation, this.baseGreen.b);
            }
            else {
                // 如果没有相邻地砖，使用基础颜色加上随机变化
                r = this.clampToBaseColor(this.baseGreen.r + Math.floor(Math.random() * this.colorVariation * 2) - this.colorVariation, this.baseGreen.r);
                g = this.clampToBaseColor(this.baseGreen.g + Math.floor(Math.random() * this.colorVariation * 2) - this.colorVariation, this.baseGreen.g);
                b = this.clampToBaseColor(this.baseGreen.b + Math.floor(Math.random() * this.colorVariation * 2) - this.colorVariation, this.baseGreen.b);
            }
            // 确保绿色值较高，保持绿色调
            g = Math.max(g, r + 40); // 绿色值至少比红色值高40
            g = Math.max(g, b + 40); // 绿色值至少比蓝色值高40
            // 转换为十六进制颜色值
            var color = (r << 16) | (g << 8) | b;
            // 保存颜色到颜色映射
            this.colorMap[key] = color;
            return color;
        };
        /**
         * 获取相邻地砖的颜色
         * @param {number} gridX 地砖的网格位置X
         * @param {number} gridY 地砖的网格位置Y
         * @returns {Array} 相邻地砖的颜色数组
         */
        IsoGeneratorGraphics.prototype.getNeighborColors = function (gridX, gridY) {
            var neighbors = [];
            var positions = [
                [gridX - 1, gridY],
                [gridX + 1, gridY],
                [gridX, gridY - 1],
                [gridX, gridY + 1]
            ];
            for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
                var _a = positions_1[_i], x = _a[0], y = _a[1];
                var key = x + "_" + y;
                if (this.colorMap[key]) {
                    neighbors.push(this.colorMap[key]);
                }
            }
            return neighbors;
        };
        /**
         * 限制颜色值在有效范围内
         * @param {number} value 颜色值
         * @returns {number} 限制后的颜色值
         */
        IsoGeneratorGraphics.prototype.clampColor = function (value) {
            return Math.max(0, Math.min(255, value));
        };
        /**
         * 限制颜色值在基准色的一定范围内
         * @param {number} value 当前颜色值
         * @param {number} baseValue 基准颜色值
         * @returns {number} 限制后的颜色值
         */
        IsoGeneratorGraphics.prototype.clampToBaseColor = function (value, baseValue) {
            var min = Math.max(0, baseValue - this.maxDeviation);
            var max = Math.min(255, baseValue + this.maxDeviation);
            return Math.max(min, Math.min(max, value));
        };
        return IsoGeneratorGraphics;
    }());
    d5.IsoGeneratorGraphics = IsoGeneratorGraphics;
    __reflect(IsoGeneratorGraphics.prototype, "d5.IsoGeneratorGraphics");
    var IsoHelper = (function () {
        function IsoHelper() {
        }
        /**
         * convert an isometric point to 2D，这里的2d坐标只不过是虚拟的，并不是真实的
         * */
        IsoHelper.isoTo2D = function (pt) {
            //gx=(2*isoy+isox)/2;
            //gy=(2*isoy-isox)/2
            var tempPt = new d5.Point(0, 0);
            tempPt.x = (2 * pt.y + pt.x) / 2;
            tempPt.y = (2 * pt.y - pt.x) / 2;
            return (tempPt);
        };
        /**
         * convert a 2d point to isometric
         * */
        IsoHelper.twoDToIso = function (pt) {
            //gx=(isox-isoxy;
            //gy=(isoy+isox)/2
            var tempPt = new d5.Point(0, 0);
            tempPt.x = pt.x - pt.y;
            tempPt.y = (pt.x + pt.y) / 2;
            return (tempPt);
        };
        /**
         * convert a 2d point to specific tile row/column
         * */
        IsoHelper.getTileCoordinates = function (pt, tileHeight) {
            var tempPt = new d5.Point(0, 0);
            tempPt.x = Math.floor(pt.x / tileHeight);
            tempPt.y = Math.floor(pt.y / tileHeight);
            return (tempPt);
        };
        /**
         * convert specific tile row/column to 2d point
         * */
        IsoHelper.get2dFromTileCoordinates = function (pt, tileHeight) {
            var tempPt = new d5.Point(0, 0);
            tempPt.x = pt.x * tileHeight;
            tempPt.y = pt.y * tileHeight;
            return (tempPt);
        };
        return IsoHelper;
    }());
    d5.IsoHelper = IsoHelper;
    __reflect(IsoHelper.prototype, "d5.IsoHelper");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    /**
 * 等角地图网格生成类
 */
    var IsoGrid = (function () {
        /**
         * 构造函数
         * @param options 配置选项
         */
        function IsoGrid(options) {
            if (options === void 0) { options = {}; }
            this._originX = 0; // 原点X坐标(世界坐标)
            this._originY = 0; // 原点Y坐标(世界坐标)
            this._offsetX = 0; // 偏移X(用于居中)
            this._offsetY = 0; // 偏移Y(用于居中)
            if (options.tileCountX !== undefined && options.tileCountY !== undefined) {
                // 方式1: 通过Tile数量初始化
                this._tileCountX = options.tileCountX;
                this._tileCountY = options.tileCountY;
                this._worldWidth = this._tileCountX * IsoGrid.TILE_WIDTH;
                this._worldHeight = this._tileCountY * IsoGrid.TILE_HEIGHT;
            }
            else if (options.worldWidth !== undefined && options.worldHeight !== undefined) {
                // 方式2: 通过世界尺寸初始化
                this._worldWidth = options.worldWidth;
                this._worldHeight = options.worldHeight;
                this._tileCountX = Math.ceil(this._worldWidth / IsoGrid.TILE_HALF_WIDTH);
                this._tileCountY = Math.ceil(this._worldHeight / IsoGrid.TILE_HALF_HEIGHT);
            }
            else {
                throw new Error("Invalid initialization parameters");
            }
            // 如果需要居中到世界中心
            if (options.centerToWorld) {
                this._offsetX = (this._worldWidth - this._tileCountX * IsoGrid.TILE_HALF_WIDTH) * 0.5;
                this._offsetY = (this._worldHeight - this._tileCountY * IsoGrid.TILE_HALF_HEIGHT) * 0.5;
            }
        }
        // ================= 公共方法 =================
        /**
         * 获取Tile的世界坐标
         * @param tileX Tile的X坐标
         * @param tileY Tile的Y坐标
         * @returns 世界坐标点
         */
        IsoGrid.prototype.getTileWorldPosition = function (tileX, tileY) {
            var x = this._originX + this._offsetX + (tileX - tileY) * IsoGrid.TILE_HALF_WIDTH;
            var y = this._originY + this._offsetY + (tileX + tileY) * IsoGrid.TILE_HALF_HEIGHT;
            return { x: x, y: y };
        };
        /**
         * 将世界坐标转换为Tile坐标
         * @param worldX 世界X坐标
         * @param worldY 世界Y坐标
         * @returns Tile坐标(可能是浮点数)
         */
        IsoGrid.prototype.worldToTile = function (worldX, worldY) {
            var localX = worldX - this._originX - this._offsetX;
            var localY = worldY - this._originY - this._offsetY;
            var tileX = (localX / IsoGrid.TILE_HALF_WIDTH + localY / IsoGrid.TILE_HALF_HEIGHT) * 0.5;
            var tileY = (localY / IsoGrid.TILE_HALF_HEIGHT - localX / IsoGrid.TILE_HALF_WIDTH) * 0.5;
            return { tileX: tileX, tileY: tileY };
        };
        /**
         * 获取周围N格范围内的Tile
         * @param worldX 世界X坐标
         * @param worldY 世界Y坐标
         * @param range 范围(格子数)
         * @returns 包含周围Tile信息的数组
         */
        IsoGrid.prototype.getSurroundingTiles = function (worldX, worldY, range) {
            if (range === void 0) { range = 3; }
            // 1. 将世界坐标转换为Tile坐标
            var _a = this.worldToTile(worldX, worldY), tileX = _a.tileX, tileY = _a.tileY;
            var centerTileX = Math.round(tileX);
            var centerTileY = Math.round(tileY);
            // 2. 计算周围Tile的范围
            var result = [];
            var minX = Math.max(0, centerTileX - range);
            var maxX = Math.min(this._tileCountX - 1, centerTileX + range);
            var minY = Math.max(0, centerTileY - range);
            var maxY = Math.min(this._tileCountY - 1, centerTileY + range);
            // 3. 收集范围内的所有Tile
            for (var y = minY; y <= maxY; y++) {
                for (var x = minX; x <= maxX; x++) {
                    // 计算曼哈顿距离(菱形范围)
                    var distance = Math.abs(x - centerTileX) + Math.abs(y - centerTileY);
                    if (distance <= range) {
                        var worldPos = this.getTileWorldPosition(x, y);
                        result.push({
                            tileX: x,
                            tileY: y,
                            worldX: worldPos.x,
                            worldY: worldPos.y,
                            isCenter: x == centerTileX && y == centerTileY
                        });
                    }
                }
            }
            return result;
        };
        /**
         * 获取所有Tile的信息(用于调试或渲染)
         */
        IsoGrid.prototype.getAllTiles = function () {
            var result = [];
            for (var y = 0; y < this._tileCountY; y++) {
                for (var x = 0; x < this._tileCountX; x++) {
                    var worldPos = this.getTileWorldPosition(x, y);
                    result.push({
                        tileX: x,
                        tileY: y,
                        worldX: worldPos.x,
                        worldY: worldPos.y
                    });
                }
            }
            return result;
        };
        Object.defineProperty(IsoGrid.prototype, "tileCountX", {
            // ================= Getter方法 =================
            get: function () {
                return this._tileCountX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(IsoGrid.prototype, "tileCountY", {
            get: function () {
                return this._tileCountY;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(IsoGrid.prototype, "worldWidth", {
            get: function () {
                return this._worldWidth;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(IsoGrid.prototype, "worldHeight", {
            get: function () {
                return this._worldHeight;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(IsoGrid.prototype, "originX", {
            get: function () {
                return this._originX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(IsoGrid.prototype, "originY", {
            get: function () {
                return this._originY;
            },
            enumerable: true,
            configurable: true
        });
        // 配置参数
        IsoGrid.TILE_WIDTH = 64; // 菱形瓦片宽度
        IsoGrid.TILE_HEIGHT = 32; // 菱形瓦片高度
        IsoGrid.TILE_HALF_WIDTH = IsoGrid.TILE_WIDTH * 0.5;
        IsoGrid.TILE_HALF_HEIGHT = IsoGrid.TILE_HEIGHT * 0.5;
        return IsoGrid;
    }());
    d5.IsoGrid = IsoGrid;
    __reflect(IsoGrid.prototype, "d5.IsoGrid");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    /**
     * IsoContainer是一个0点在左上角（菱形上顶点），向右下45°为X正方向，向左下45°为Y正方向的等角坐标系统
     */
    var IsoContainer = (function (_super) {
        __extends(IsoContainer, _super);
        function IsoContainer(w, h, xoffset, yoffset, needOffsetRelatedCenter) {
            if (xoffset === void 0) { xoffset = 0; }
            if (yoffset === void 0) { yoffset = 0; }
            if (needOffsetRelatedCenter === void 0) { needOffsetRelatedCenter = false; }
            var _this = _super.call(this) || this;
            _this.centerOffsetx = 0; //相对于virtualRec进行的偏差
            _this.centerOffsety = 0;
            _this._objects = [];
            _this._objectsContainer = new d5.DisplayContainer();
            _this._virtualRecZero = new d5.Point();
            if (IsoContainer.tileData == null) {
                var shape = new PIXI.Graphics()
                    .moveTo(IsoContainer.Tile_Width * .5, 0)
                    .lineTo(IsoContainer.Tile_Width, IsoContainer.Tile_Width * .25)
                    .lineTo(IsoContainer.Tile_Width * .5, IsoContainer.Tile_Width * .5)
                    .lineTo(0, IsoContainer.Tile_Width * .25)
                    .lineTo(IsoContainer.Tile_Width * .5, 0)
                    .stroke({ width: 1, color: 0xffffff, alpha: 0.5 });
                IsoContainer.tileData = PIXI.RenderTexture.create({ width: IsoContainer.Tile_Width, height: IsoContainer.Tile_Width * .5 });
                D5Power.renderer.render(shape, { renderTexture: IsoContainer.tileData });
                IsoContainer.offsetMx.tx = -IsoContainer.Square_Width;
                _this._needOffsetRelatedCenter = needOffsetRelatedCenter;
                _this.update(w, h, xoffset, yoffset);
            }
            return _this;
        }
        /**
         * 向场景中添加对象
         * @param o
         * @param tx tile坐标X
         * @param ty tile坐标Y
         * @param conf 地图占用
         * @returns
         */
        IsoContainer.prototype.addObject = function (o, tx, ty, conf) {
            if (conf === void 0) { conf = null; }
            if (tx > this._num || ty > this._num) {
                console.log("[IsoContainer.addObject] 超出地图范围");
                return;
            }
            var p = this.isoTo2D(tx, ty);
            o.setPosition(p.x, p.y);
            // 处理conf表示的地图占位
            if (conf !== null && this._roadMap) {
                // 如果conf是数值，则设置当前坐标的通过状态
                if (typeof conf === 'number') {
                    // 边界控制，超出地图边界无需处理
                    if (tx >= 0 && tx < this._num && ty >= 0 && ty < this._num) {
                        // 设置可通过性：conf为0表示可通过（true），非0表示不可通过（false）
                        this._roadMap.setWalkable(tx, ty, conf === 0);
                    }
                }
                else if (Array.isArray(conf)) {
                    for (var i = 0; i < conf.length; i++) {
                        var offx = conf[i][0]; // 相对于tx的偏移坐标X
                        var offy = conf[i][1]; // 相对于ty的偏移坐标Y
                        var obs = conf[i][2]; // 占位值，0表示可通过，不为0则不能通过
                        // 计算实际地图坐标
                        var mapX = tx + offx;
                        var mapY = ty + offy;
                        // 边界控制，超出地图边界无需处理
                        if (mapX >= 0 && mapX < this._num && mapY >= 0 && mapY < this._num) {
                            // 设置可通过性：obs为0表示可通过（true），非0表示不可通过（false）
                            this._roadMap.setWalkable(mapX, mapY, obs === 0);
                        }
                    }
                }
            }
            // 将对象添加到容器中
            this._objectsContainer.addChild(o);
            this._objects.push(o);
        };
        IsoContainer.prototype.setObjectIndex = function (v, index) {
            this._objectsContainer.setChildIndex(v, index);
        };
        IsoContainer.prototype.getObjectAt = function (index) {
            return index < this.numChildren ? this._objectsContainer.getChildAt(index) : null;
        };
        Object.defineProperty(IsoContainer.prototype, "objects", {
            get: function () {
                return this._objects;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * 寻路
         * @param xnow
         * @param ynow
         * @param xto
         * @param yto
         */
        IsoContainer.prototype.findPath = function (xnow, ynow, xto, yto) {
            return this._roadMap.find(xnow, ynow, xto, yto);
        };
        IsoContainer.prototype.updateRoadMap = function (roadmap) {
            this._roadMap = new d5.SilzAstar(roadmap);
        };
        Object.defineProperty(IsoContainer.prototype, "nh", {
            get: function () {
                return this._nh;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(IsoContainer.prototype, "nw", {
            get: function () {
                return this._nw;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * 获取点击位置周围指定个格子的tile的网格信息
         * @param worldX 点击的世界坐标X
         * @param worldY 点击的世界坐标Y
         * @param radius 半径
         * @returns 返回包含周围10个tile信息的数组，每个元素是{tileX, tileY, screenX, screenY}
         */
        IsoContainer.prototype.getSurroundingTiles = function (worldX, worldY, radius) {
            if (radius === void 0) { radius = 10; }
            // 1. 将世界坐标转换为等角坐标系的坐标
            var localPoint = this.globalToLocal(new d5.Point(worldX, worldY));
            var isoPoint = d5.IsoHelper.twoDToIso(localPoint);
            // 2. 计算点击位置所在的tile坐标
            var tileX = Math.floor(isoPoint.x / IsoContainer.Square_Width);
            var tileY = Math.floor(isoPoint.y / IsoContainer.Square_Width);
            // 3. 计算周围10个tile的范围
            var surroundingTiles = [];
            for (var y = tileY - radius; y <= tileY + radius; y++) {
                for (var x = tileX - radius; x <= tileX + radius; x++) {
                    // 确保只收集大约10个最接近的tile
                    if (Math.abs(x - tileX) + Math.abs(y - tileY) <= radius) {
                        // 计算tile在屏幕上的位置
                        var screenPos = new d5.Point(x * IsoContainer.Square_Width, y * IsoContainer.Square_Width);
                        var isoPos = d5.IsoHelper.twoDToIso(screenPos);
                        // 转换为世界坐标
                        var worldPos = this.localToGlobal(isoPos);
                        // 添加到结果数组
                        surroundingTiles.push({
                            tileX: x + this._zeroPointX,
                            tileY: y + this._zeroPointY,
                            worldX: worldPos.x,
                            worldY: worldPos.y,
                            isCenter: x == tileX && y == tileY
                        });
                    }
                }
            }
            return surroundingTiles;
        };
        /**
         * 辅助方法：将世界坐标转换为容器本地坐标
         */
        IsoContainer.prototype.globalToLocal = function (point) {
            return new d5.Point(point.x - this.x - this.centerOffsetx, point.y - this.y - this.centerOffsety);
        };
        /**
         * 辅助方法：将容器本地坐标转换为世界坐标
         */
        IsoContainer.prototype.localToGlobal = function (point) {
            return new d5.Point(point.x + this.x + this.centerOffsetx, point.y + this.y + this.centerOffsety);
        };
        IsoContainer.prototype.update = function (w, h, xoffset, yoffset, leftTopPoint) {
            if (leftTopPoint === void 0) { leftTopPoint = null; }
            this._w = w;
            this._h = h;
            this._xoffset = xoffset;
            this._yoffset = yoffset;
            this._widthDirection = Math.ceil(this._w / IsoContainer.Tile_Width);
            this._heightDirection = Math.ceil(this._h / (IsoContainer.Tile_Width * .5));
            this._num = this._widthDirection + this._heightDirection;
            this._width = this._num * IsoContainer.Tile_Width;
            this._height = this._num * IsoContainer.Tile_Width * .5;
            this._nw = this._widthDirection * IsoContainer.Tile_Width;
            this._nh = this._heightDirection * IsoContainer.Tile_Width * .5;
            this._virtualRecZero.x = 0 * IsoContainer.Square_Width;
            this._virtualRecZero.y = this._widthDirection * IsoContainer.Square_Width;
            this._virtualRecZero = d5.IsoHelper.twoDToIso(this._virtualRecZero);
            this._virtualRec = new d5.Rectangle(this._virtualRecZero.x, this._virtualRecZero.y, this._nw, this._nh);
            this._endX = this._virtualRec.width - Math.abs(this._virtualRec.x);
            this._endY = this._virtualRec.height + this._virtualRecZero.y;
            if (leftTopPoint) {
                this._zeroPointX = leftTopPoint.x;
                this._zeroPointY = leftTopPoint.y - this._widthDirection;
            }
            var roadMap = [];
            for (var py = 0; py < this._num; py++) {
                var line = [];
                for (var px = 0; px < this._num; px++) {
                    line.push(0);
                }
                roadMap.push(line);
            }
            this.updateRoadMap(roadMap);
            if (this._needOffsetRelatedCenter)
                this.updateCoordinate();
        };
        Object.defineProperty(IsoContainer.prototype, "n", {
            get: function () {
                return this._num;
            },
            enumerable: true,
            configurable: true
        });
        IsoContainer.prototype.draw = function (isShowAll, gridType) {
            if (isShowAll === void 0) { isShowAll = true; }
            if (gridType === void 0) { gridType = 0; }
            //			updateCoordinate()
            this._gridType = gridType;
            this._isShowAll = isShowAll;
            this.updateTiles();
        };
        IsoContainer.prototype.updateCoordinate = function () {
            var tempx = this.x;
            var tempy = this.y;
            this.x = (this._nw - this._width) * .5 + this._xoffset;
            this.y = (this._nh - this._height) * .5 + this._yoffset;
            this.x += this._num * IsoContainer.Tile_Width * .5;
            this.centerOffsetx = tempx - this.x;
            this.centerOffsety = tempy - this.y;
        };
        IsoContainer.prototype.setFillTiles = function (fillData) {
            this._fillData = fillData;
        };
        IsoContainer.prototype.updateTiles = function () {
            this.tileList = {};
            this.removeChildren();
            var p;
            var tile;
            var cp;
            var fillColor;
            for (var i = 0; i < this._num; ++i) {
                for (var j = 0; j < this._num; ++j) {
                    p = new d5.Point();
                    p.x = j * IsoContainer.Square_Width;
                    p.y = i * IsoContainer.Square_Width;
                    p = d5.IsoHelper.twoDToIso(p);
                    cp = this.getTileCenterPos(p.x, p.y);
                    fillColor = this._fillData ? this._fillData[i * this._num + j] : 0;
                    if (!this._isShowAll) {
                        if (this.isInRect(cp.x, cp.y)) {
                            tile = IsoContainer.getTile(fillColor ? fillColor : NaN);
                            tile.x = p.x;
                            tile.y = p.y;
                            this.addChild(tile);
                            tile.name = j + '_' + i;
                            this.tileList[tile.name] = tile;
                        }
                    }
                    else {
                        tile = IsoContainer.getTile(fillColor ? fillColor : NaN);
                        tile.x = p.x;
                        tile.y = p.y;
                        this.addChild(tile);
                        tile.name = j + '_' + i;
                        this.tileList[tile.name] = tile;
                        //						trace('iso',j,i);
                    }
                }
            }
            this.addChild(this._objectsContainer);
        };
        /**
         * 2D坐标转换为等距地图坐标，这里的2D坐标并非屏幕坐标，而是等距地图中的世界坐标
         * @param px
         * @param py
         * @returns
         */
        IsoContainer.prototype.twoDToIso = function (px, py) {
            var p = new d5.Point();
            p.x = px - this.x;
            py = py - this.y;
            p = d5.IsoHelper.twoDToIso(p);
            trace(this.x, this.y);
            return p;
        };
        /**
         * 把一个地砖坐标，转换为屏幕坐标
         * @param tx
         * @param ty
         * @returns
         */
        IsoContainer.prototype.isoTo2D = function (tx, ty) {
            var p = new d5.Point();
            p.x = tx * IsoContainer.Square_Width;
            p.y = ty * IsoContainer.Square_Width;
            p = d5.IsoHelper.twoDToIso(p);
            p = this.getTileCenterPos(p.x, p.y);
            p.x += d5.IsoContainer.Tile_Width * .5;
            return p;
        };
        /**
         *
         * @param tx
         * @param ty
         * @returns
         */
        IsoContainer.prototype.getTileCenterPos = function (tx, ty) {
            var p = new d5.Point();
            ty += IsoContainer.Tile_Width * .25;
            p.x = tx;
            p.y = ty;
            return p;
        };
        IsoContainer.getTile = function (color) {
            if (color === void 0) { color = NaN; }
            //此菱形的注册点位于top
            var s;
            if (isNaN(color)) {
                s = new PIXI.Sprite(IsoContainer.tileData);
                s.anchor.set(0.5);
            }
            else {
                s = new PIXI.Graphics()
                    .moveTo(IsoContainer.Tile_Width * .5, 0)
                    .lineTo(IsoContainer.Tile_Width, IsoContainer.Tile_Width * .25)
                    .lineTo(IsoContainer.Tile_Width * .5, IsoContainer.Tile_Width * .5)
                    .lineTo(0, IsoContainer.Tile_Width * .25)
                    .lineTo(IsoContainer.Tile_Width * .5, 0)
                    .fill({ color: color });
            }
            return s;
        };
        IsoContainer.prototype.isInRect = function (x, y) {
            if (x >= this._virtualRecZero.x && x <= this._endX && y >= this._virtualRecZero.y && y <= this._endY) {
                return true;
            }
            return false;
        };
        /**
         * 相对于世界地图的坐标
         * @param p
         * @return
         *
         */
        IsoContainer.prototype.getCoordinateRelatedWorldMap = function (p) {
            p.x -= this._virtualRecZero.x; //virtualRecZero相当于世界坐标的0，0点
            p.y -= this._virtualRecZero.y;
            //			p.x -= centerOffsetx;
            //			p.y -= centerOffsety;
            return p;
        };
        Object.defineProperty(IsoContainer.prototype, "virtualZero", {
            get: function () {
                return this._virtualRecZero;
            },
            enumerable: true,
            configurable: true
        });
        // @ts-ignore
        IsoContainer.offsetMx = new d5.Matrix(1, 0, 0, 1, -32);
        IsoContainer.Tile_Width = 64; //iso diamond的widht,其height为32s
        IsoContainer.Square_Width = IsoContainer.Tile_Width * .5;
        return IsoContainer;
    }(d5.DisplayContainer));
    d5.IsoContainer = IsoContainer;
    __reflect(IsoContainer.prototype, "d5.IsoContainer");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var Camera = (function () {
        function Camera() {
            /**
             * 相机缩放值
             */
            this._zoom = 1;
            /**
             * 目标缩放值
             */
            this._targetZoom = 1;
            this._zoomEasing = 0.1;
            /**
             * 屏幕中心点X坐标
             */
            this._centerX = 0;
            /**
             * 屏幕中心点Y坐标
             */
            this._centerY = 0;
            this._lastSort = 0;
        }
        Object.defineProperty(Camera.prototype, "screen", {
            /**
             * 设置整体场景
             */
            set: function (v) {
                this._screen = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera.prototype, "focus", {
            /**
             * 设置相机观察的目标
             * 被观察的目标将始终位于屏幕中心
             */
            set: function (v) {
                this._focus = v;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera.prototype, "zoom", {
            /**
             * 获取当前缩放值
             */
            get: function () {
                return this._zoom;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * 设置屏幕中心点
         */
        Camera.prototype.setCenter = function (x, y) {
            this._centerX = x;
            this._centerY = y;
        };
        /**
         * 启动相机，开始渲染循环
         */
        Camera.prototype.start = function () {
            var _this = this;
            D5Power.addEnterframe(function () { return _this.update(); });
        };
        /**
         * 停止相机渲染循环
         */
        Camera.prototype.stop = function () {
            var _this = this;
            D5Power.removeEnterframe(function () { return _this.update(); });
        };
        Camera.prototype.deepSortCau = function (orderA, orderB) {
            return (orderA.y - orderB.y) * 100 + orderA.x - orderB.x;
        };
        Camera.prototype.deepSort = function (t) {
            if (this._lastSort == 0 || t - this._lastSort > 200) {
                var list = this._screen['objects'];
                list.sort(this.deepSortCau);
                var orderCount = list.length;
                // 交换层次对象
                var child; // 场景对象
                var child_now;
                while (orderCount--) {
                    child_now = list[orderCount];
                    if (orderCount < this._screen.numChildren) {
                        // @ts-ignore
                        child = this._screen.getObjectAt(orderCount);
                        if (child != child_now) {
                            // @ts-ignore
                            this._screen.setObjectIndex(child_now, orderCount);
                        }
                    }
                }
                this._lastSort = t;
            }
        };
        /**
         * 镜头缩放，通过整体缩放容器来实现
         * 趋近于0为放大容器使镜头趋近观察目标，1为整体容器的缩放为1，大于0为缩小容器，镜头远离观察目标
         * @param v 目标缩放值
         * @param easing 可选，缓动系数，默认使用类默认值
         */
        Camera.prototype.zoomTo = function (v, easing) {
            var _this = this;
            if (easing === void 0) { easing = NaN; }
            if (easing > 0.5)
                easing = 0.5;
            if (easing < 0.1)
                easing = 0.1;
            return new Promise(function (resolve, reject) {
                if (!_this._screen) {
                    reject();
                    return;
                }
                _this._targetZoom = v;
                if (!isNaN(easing)) {
                    _this._zoomEasing = easing;
                    var that_1 = _this;
                    D5Power.addEnterframe(function () {
                        if (Math.abs(that_1._zoom - that_1._targetZoom) > 0.001) {
                            that_1._zoom += (that_1._targetZoom - that_1._zoom) * that_1._zoomEasing;
                            that_1._screen.scale = that_1._zoom;
                            that_1.update();
                        }
                        else {
                            D5Power.removeEnterframe(this);
                            resolve();
                        }
                    });
                }
            });
        };
        Camera.prototype.update = function () {
            if (!this._screen || !this._focus)
                return;
            // 使用D5Power.stageWidth和D5Power.stageHeight获取屏幕尺寸
            var screenWidth = D5Power.stageWidth;
            var screenHeight = D5Power.stageHeight;
            // 计算屏幕中心点
            var centerX = screenWidth / 2;
            var centerY = screenHeight / 2;
            // 计算焦点对象的世界坐标
            var focusWorldX = this._focus.x;
            var focusWorldY = this._focus.y;
            // 计算场景应该偏移的坐标，使焦点对象位于屏幕中心
            // 公式：屏幕中心点 - 焦点对象坐标 * 缩放比例
            var targetOffsetX = centerX - focusWorldX * this._zoom;
            var targetOffsetY = centerY - focusWorldY * this._zoom;
            // 设置场景的偏移坐标
            this._screen.offsetX = targetOffsetX;
            this._screen.offsetY = targetOffsetY;
            // 更新场景容器的位置
            this._screen.x = targetOffsetX;
            this._screen.y = targetOffsetY;
            this.deepSort(D5Power.getTimer());
        };
        return Camera;
    }());
    d5.Camera = Camera;
    __reflect(Camera.prototype, "d5.Camera");
})(d5 || (d5 = {}));
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, MicroGame Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
var d5;
(function (d5) {
    var SilzAstar = (function () {
        /**
         * @param    mapdata        地图数据
         * @param    container    显示容器，若为null则不显示地图
         */
        function SilzAstar(mapdata, workmode, debug) {
            if (workmode === void 0) { workmode = 4; }
            if (debug === void 0) { debug = false; }
            /**
             * 寻路方式，8方向和4方向，有效值为8和4
             */
            this._WorkMode = 4;
            /**
             * 地图显示尺寸
             */
            this._cellSize = 5;
            /**
             * 显示模式
             */
            this.isDisplayMode = false;
            this.isDisplayMode = debug;
            if (workmode != 4)
                workmode = 8;
            this._WorkMode = workmode;
            this.makeGrid(mapdata);
        }
        /**
         * @param        xnow    当前坐标X(寻路格子坐标)
         * @param        ynow    当前坐标Y(寻路格子坐标)
         * @param        xpos    目标点X(寻路格子坐标)
         * @param        ypos    目标点Y(寻路格子坐标)
         */
        SilzAstar.prototype.find = function (xnow, ynow, xpos, ypos) {
            xpos = Math.min(xpos, this._grid.numCols - 1);
            ypos = Math.min(ypos, this._grid.numRows - 1);
            xpos = Math.max(xpos, 0);
            ypos = Math.max(ypos, 0);
            var initTime = D5Power.getTimer();
            var runTime = 0;
            // 超出寻路范围
            if (!this._grid.nodeValuable(xpos, ypos))
                return null;
            this._grid.setEndNode(xpos, ypos); //1
            xnow = Math.min(xnow, this._grid.numCols - 1);
            ynow = Math.min(ynow, this._grid.numRows - 1);
            xnow = Math.max(xnow, 0);
            ynow = Math.max(ynow, 0);
            if (!this._grid.nodeValuable(xnow, ynow))
                return null;
            this._grid.setStartNode(xnow, ynow); //2
            if (this.isDisplayMode) {
                runTime = initTime;
            }
            if (this.astar.findPath()) {
                this._index = 0;
                this.astar.floyd();
                this._path = this.astar.floydPath;
                if (this.isDisplayMode) {
                    runTime = initTime - runTime;
                    console.log("[SilzAstar]", runTime + "ms   length:" + this.astar.path.length);
                    console.log("[SilzAstar]", this.astar.floydPath);
                    //this.path.graphics.clear();
                    for (var i = 0; i < this.astar.floydPath.length; i++) {
                        var p = this.astar.floydPath[i];
                        trace(p.x, p.y);
                        //this.path.graphics.lineStyle(0, 0xff0000);
                        //this.path.graphics.drawCircle((p.x + 0.5) * this._cellSize, (p.y + 0.5) * this._cellSize, 2);
                        //this.path.graphics.lineStyle(0, 0xff0000, 0.5);
                        //this.path.graphics.moveTo(xnow, ynow);
                    }
                }
                return this._path;
            }
            else if (this.isDisplayMode) {
                this._grid.setEndNode(xpos - 1, ypos - 1);
                runTime = initTime - runTime;
                console.log("[SilzAstar]", runTime + "ms 找不到");
            }
            return null;
        };
        SilzAstar.prototype.makeGrid = function (data) {
            var rows = data.length;
            var cols = data[0].length;
            this._grid = new Grid(cols, rows);
            var px;
            var py;
            for (py = 0; py < rows; py++) {
                for (px = 0; px < cols; px++) {
                    this._grid.setWalkable(px, py, data[py][px] == 0);
                }
            }
            if (this._WorkMode == 4)
                this._grid.calculateLinks(1);
            else
                this._grid.calculateLinks();
            this.astar = new AStar(this._grid);
            if (this.isDisplayMode) {
                this.drawGrid();
                //this.path.graphics.clear();
            }
        };
        SilzAstar.prototype.drawGrid = function () {
            console.log("fuck");
            //			this.image.bitmapData = new BitmapData(this._grid.numCols * this._cellSize, this._grid.numRows * this._cellSize, false, 0xffffff);
            //			for (var i:number = 0; i < this._grid.numCols; i++){
            //				for (var j:number = 0; j < this._grid.numRows; j++){
            //					var node:SilzAstarNode = this._grid.getNode(i, j);
            //					if (!node.walkable){
            //						this.image.bitmapData.fillRect(new egret.Rectangle(i * this._cellSize, j * this._cellSize, this._cellSize, this._cellSize), this.getColor(node));
            //					}
            //				}
            //			}
        };
        SilzAstar.prototype.getColor = function (node) {
            if (!node.walkable)
                return 0;
            if (node == this._grid.startNode)
                return 0xcccccc;
            if (node == this._grid.endNode)
                return 0xcccccc;
            return 0xffffff;
        };
        SilzAstar.prototype.setWalkable = function (tx, ty, walkable) {
            this._grid.setWalkable(tx, ty, walkable);
        };
        SilzAstar.prototype.getWalkable = function (tx, ty) {
            return this._grid.getWalkable(tx, ty);
        };
        return SilzAstar;
    }());
    d5.SilzAstar = SilzAstar;
    __reflect(SilzAstar.prototype, "d5.SilzAstar");
    var AStar = (function () {
        function AStar(grid) {
            this._straightCost = 1.0;
            this._diagCost = Math.SQRT2;
            this.nowversion = 1;
            this.TwoOneTwoZero = 2 * Math.cos(Math.PI / 3);
            this._grid = grid;
            this.heuristic = this.euclidian2;
        }
        AStar.prototype.justMin = function (x, y) {
            return x.f < y.f;
        };
        AStar.prototype.findPath = function () {
            this._endNode = this._grid.endNode;
            this.nowversion++;
            this._startNode = this._grid.startNode;
            //_open = [];
            this._open = new BinaryHeap(this.justMin);
            this._startNode.g = 0;
            return this.search();
        };
        AStar.prototype.floyd = function () {
            if (this.path == null)
                return;
            this._floydPath = this.path.concat();
            var len = this._floydPath.length;
            if (len > 2) {
                var vector = new SilzAstarNode(0, 0);
                var tempVector = new SilzAstarNode(0, 0);
                this.floydVector(vector, this._floydPath[len - 1], this._floydPath[len - 2]);
                for (var i = this._floydPath.length - 3; i >= 0; i--) {
                    this.floydVector(tempVector, this._floydPath[i + 1], this._floydPath[i]);
                    if (vector.x == tempVector.x && vector.y == tempVector.y) {
                        this._floydPath.splice(i + 1, 1);
                    }
                    else {
                        vector.x = tempVector.x;
                        vector.y = tempVector.y;
                    }
                }
            }
            len = this._floydPath.length;
            for (i = len - 1; i >= 0; i--) {
                for (var j = 0; j <= i - 2; j++) {
                    if (this.floydCrossAble(this._floydPath[i], this._floydPath[j])) {
                        for (var k = i - 1; k > j; k--) {
                            this._floydPath.splice(k, 1);
                        }
                        i = j;
                        len = this._floydPath.length;
                        break;
                    }
                }
            }
        };
        AStar.prototype.floydCrossAble = function (n1, n2) {
            var ps = this.bresenhamNodes(new d5.Point(n1.x, n1.y), new d5.Point(n2.x, n2.y));
            for (var i = ps.length - 2; i > 0; i--) {
                if (!this._grid.getNode(ps[i].x, ps[i].y).walkable) {
                    return false;
                }
            }
            return true;
        };
        AStar.prototype.bresenhamNodes = function (p1, p2) {
            var steep = Math.abs(p2.y - p1.y) > Math.abs(p2.x - p1.x);
            if (steep) {
                var temp = p1.x;
                p1.x = p1.y;
                p1.y = temp;
                temp = p2.x;
                p2.x = p2.y;
                p2.y = temp;
            }
            var stepX = p2.x > p1.x ? 1 : (p2.x < p1.x ? -1 : 0);
            var stepY = p2.y > p1.y ? 1 : (p2.y < p1.y ? -1 : 0);
            var deltay = (p2.y - p1.y) / Math.abs(p2.x - p1.x);
            var ret = [];
            var nowX = p1.x + stepX;
            var nowY = p1.y + deltay;
            if (steep) {
                ret.push(new d5.Point(p1.y, p1.x));
            }
            else {
                ret.push(new d5.Point(p1.x, p1.y));
            }
            while (nowX != p2.x) {
                var fy = Math.floor(nowY);
                var cy = Math.ceil(nowY);
                if (steep) {
                    ret.push(new d5.Point(fy, nowX));
                }
                else {
                    ret.push(new d5.Point(nowX, fy));
                }
                if (fy != cy) {
                    if (steep) {
                        ret.push(new d5.Point(cy, nowX));
                    }
                    else {
                        ret.push(new d5.Point(nowX, cy));
                    }
                }
                nowX += stepX;
                nowY += deltay;
            }
            if (steep) {
                ret.push(new d5.Point(p2.y, p2.x));
            }
            else {
                ret.push(new d5.Point(p2.x, p2.y));
            }
            return ret;
        };
        AStar.prototype.floydVector = function (target, n1, n2) {
            target.x = n1.x - n2.x;
            target.y = n1.y - n2.y;
        };
        AStar.prototype.search = function () {
            var node = this._startNode;
            node.version = this.nowversion;
            while (node != this._endNode) {
                var len = node.links.length;
                for (var i = 0; i < len; i++) {
                    var test = node.links[i].node;
                    var cost = node.links[i].cost;
                    var g = node.g + cost;
                    var h = this.heuristic(test);
                    var f = g + h;
                    if (test.version == this.nowversion) {
                        if (test.f > f) {
                            test.f = f;
                            test.g = g;
                            test.h = h;
                            test.parent = node;
                        }
                    }
                    else {
                        test.f = f;
                        test.g = g;
                        test.h = h;
                        test.parent = node;
                        this._open.ins(test);
                        test.version = this.nowversion;
                    }
                }
                if (this._open.a.length == 1) {
                    return false;
                }
                node = (this._open.pop());
            }
            this.buildPath();
            return true;
        };
        AStar.prototype.buildPath = function () {
            this._path = [];
            var node = this._endNode;
            this._path.push(node);
            while (node != this._startNode) {
                node = node.parent;
                this._path.unshift(node);
            }
        };
        Object.defineProperty(AStar.prototype, "path", {
            get: function () {
                return this._path;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AStar.prototype, "floydPath", {
            get: function () {
                return this._floydPath;
            },
            enumerable: true,
            configurable: true
        });
        AStar.prototype.manhattan = function (node) {
            return Math.abs(node.x - this._endNode.x) + Math.abs(node.y - this._endNode.y);
        };
        AStar.prototype.manhattan2 = function (node) {
            var dx = Math.abs(node.x - this._endNode.x);
            var dy = Math.abs(node.y - this._endNode.y);
            return dx + dy + Math.abs(dx - dy) / 1000;
        };
        AStar.prototype.euclidian = function (node) {
            var dx = node.x - this._endNode.x;
            var dy = node.y - this._endNode.y;
            return Math.sqrt(dx * dx + dy * dy);
        };
        AStar.prototype.chineseCheckersEuclidian2 = function (node) {
            var y = node.y / this.TwoOneTwoZero;
            var x = node.x + node.y / 2;
            var dx = x - this._endNode.x - this._endNode.y / 2;
            var dy = y - this._endNode.y / this.TwoOneTwoZero;
            return this.sqrt(dx * dx + dy * dy);
        };
        AStar.prototype.sqrt = function (x) {
            return Math.sqrt(x);
        };
        AStar.prototype.euclidian2 = function (node) {
            var dx = node.x - this._endNode.x;
            var dy = node.y - this._endNode.y;
            return dx * dx + dy * dy;
        };
        AStar.prototype.diagonal = function (node) {
            var dx = Math.abs(node.x - this._endNode.x);
            var dy = Math.abs(node.y - this._endNode.y);
            var diag = Math.min(dx, dy);
            var straight = dx + dy;
            return this._diagCost * diag + this._straightCost * (straight - 2 * diag);
        };
        return AStar;
    }());
    d5.AStar = AStar;
    __reflect(AStar.prototype, "d5.AStar");
    var BinaryHeap = (function () {
        function BinaryHeap(justMinFun) {
            if (justMinFun === void 0) { justMinFun = null; }
            this.a = [];
            this.justMinFun = function (x, y) {
                return this.x < this.y;
            };
            this.a.push(-1);
            if (justMinFun != null)
                this.justMinFun = justMinFun;
        }
        BinaryHeap.prototype.ins = function (value) {
            var p = this.a.length;
            this.a[p] = value;
            var pp = p >> 1;
            while (p > 1 && this.justMinFun(this.a[p], this.a[pp])) {
                var temp = this.a[p];
                this.a[p] = this.a[pp];
                this.a[pp] = temp;
                p = pp;
                pp = p >> 1;
            }
        };
        BinaryHeap.prototype.pop = function () {
            var min = this.a[1];
            this.a[1] = this.a[this.a.length - 1];
            this.a.pop();
            var p = 1;
            var l = this.a.length;
            var sp1 = p << 1;
            var sp2 = sp1 + 1;
            while (sp1 < l) {
                if (sp2 < l) {
                    var minp = this.justMinFun(this.a[sp2], this.a[sp1]) ? sp2 : sp1;
                }
                else {
                    minp = sp1;
                }
                if (this.justMinFun(this.a[minp], this.a[p])) {
                    var temp = this.a[p];
                    this.a[p] = this.a[minp];
                    this.a[minp] = temp;
                    p = minp;
                    sp1 = p << 1;
                    sp2 = sp1 + 1;
                }
                else {
                    break;
                }
            }
            return min;
        };
        return BinaryHeap;
    }());
    d5.BinaryHeap = BinaryHeap;
    __reflect(BinaryHeap.prototype, "d5.BinaryHeap");
    var Grid = (function () {
        function Grid(numCols, numRows) {
            this._straightCost = 1.0;
            this._diagCost = Math.SQRT2;
            this._numCols = numCols;
            this._numRows = numRows;
            this._nodes = new Array();
            for (var i = 0; i < this._numCols; i++) {
                this._nodes[i] = new Array();
                for (var j = 0; j < this._numRows; j++) {
                    this._nodes[i][j] = new SilzAstarNode(i, j);
                }
            }
        }
        /**
         *
         * @param   type    0四方向 1八方向 2跳棋
         */
        Grid.prototype.calculateLinks = function (type) {
            if (type === void 0) { type = 0; }
            this.type = type;
            for (var i = 0; i < this._numCols; i++) {
                for (var j = 0; j < this._numRows; j++) {
                    this.initNodeLink(this._nodes[i][j], type);
                }
            }
        };
        Grid.prototype.getType = function () {
            return this.type;
        };
        /**
         *
         * @param   node
         * @param   type    0八方向 1四方向 2跳棋
         */
        Grid.prototype.initNodeLink = function (node, type) {
            var startX = Math.max(0, node.x - 1);
            var endX = Math.min(this.numCols - 1, node.x + 1);
            var startY = Math.max(0, node.y - 1);
            var endY = Math.min(this.numRows - 1, node.y + 1);
            node.links = [];
            for (var i = startX; i <= endX; i++) {
                for (var j = startY; j <= endY; j++) {
                    var test = this.getNode(i, j);
                    if (test == node || !test.walkable) {
                        continue;
                    }
                    if (type != 2 && i != node.x && j != node.y) {
                        var test2 = this.getNode(node.x, j);
                        if (!test2.walkable) {
                            continue;
                        }
                        test2 = this.getNode(i, node.y);
                        if (!test2.walkable) {
                            continue;
                        }
                    }
                    var cost = this._straightCost;
                    if (!((node.x == test.x) || (node.y == test.y))) {
                        if (type == 1) {
                            continue;
                        }
                        if (type == 2 && (node.x - test.x) * (node.y - test.y) == 1) {
                            continue;
                        }
                        if (type == 2) {
                            cost = this._straightCost;
                        }
                        else {
                            cost = this._diagCost;
                        }
                    }
                    node.links.push(new Link(test, cost));
                }
            }
        };
        Grid.prototype.nodeValuable = function (x, y) {
            if (!this._nodes || !this._nodes[x] || !this._nodes[x][y])
                return false;
            return true;
        };
        Grid.prototype.getNode = function (x, y) {
            return this._nodes[x][y];
        };
        Grid.prototype.setEndNode = function (x, y) {
            this._endNode = this._nodes[x][y];
        };
        Grid.prototype.setStartNode = function (x, y) {
            this._startNode = this._nodes[x][y];
        };
        Grid.prototype.setWalkable = function (x, y, value) {
            this._nodes[x][y].walkable = value;
        };
        Grid.prototype.getWalkable = function (x, y) {
            return this._nodes[x][y].walkable ? 0 : 1;
        };
        Object.defineProperty(Grid.prototype, "endNode", {
            get: function () {
                return this._endNode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Grid.prototype, "numCols", {
            get: function () {
                return this._numCols;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Grid.prototype, "numRows", {
            get: function () {
                return this._numRows;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Grid.prototype, "startNode", {
            get: function () {
                return this._startNode;
            },
            enumerable: true,
            configurable: true
        });
        return Grid;
    }());
    d5.Grid = Grid;
    __reflect(Grid.prototype, "d5.Grid");
    var Link = (function () {
        function Link(node, cost) {
            this.node = node;
            this.cost = cost;
        }
        return Link;
    }());
    d5.Link = Link;
    __reflect(Link.prototype, "d5.Link");
    var SilzAstarNode = (function () {
        //public var index:int;
        function SilzAstarNode(x, y) {
            this.walkable = true;
            //public var costMultiplier:Number = 1.0;
            this.version = 1;
            this.x = x;
            this.y = y;
        }
        SilzAstarNode.prototype.toString = function () {
            return "x:" + this.x + " y:" + this.y;
        };
        return SilzAstarNode;
    }());
    d5.SilzAstarNode = SilzAstarNode;
    __reflect(SilzAstarNode.prototype, "d5.SilzAstarNode");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    var Menu = (function (_super) {
        __extends(Menu, _super);
        function Menu(fontsize, h, bgColor, fontColor, hoverColor) {
            if (fontsize === void 0) { fontsize = 14; }
            if (h === void 0) { h = 36; }
            if (bgColor === void 0) { bgColor = 0x333333; }
            if (fontColor === void 0) { fontColor = 0xffffff; }
            if (hoverColor === void 0) { hoverColor = 0x444444; }
            var _this = _super.call(this) || this;
            _this._bg = new PIXI.Graphics();
            _this._fontSize = fontsize;
            _this._menuHeight = h;
            _this._bgColor = bgColor;
            _this._fontColor = fontColor;
            _this._hoverColor = hoverColor;
            _this._hbox = new d5.D5HBox();
            _this.asyncDraw();
            _this._monitor.addChild(_this._bg);
            _this.addChild(_this._hbox);
            return _this;
        }
        Menu.prototype.clearDown = function () {
            this._downMenu = null;
            Menu._nowDown = null;
        };
        Menu.prototype.menuOffset = function (px, py) {
            this._hbox.setPosition(px, py);
        };
        Menu.prototype.draw = function () {
            this._bg.clear();
            this._bg.rect(0, 0, D5Power.stageWidth, this._menuHeight);
            this._bg.fill({ color: this._bgColor });
        };
        Menu.prototype.setup = function (conf) {
            var btn;
            var that = this;
            var birthTime = 0;
            var onMouseOver = function (e) {
                if (that._downMenu && Menu._nowDown != e.target.d5component) {
                    onDownMenu(e);
                }
            };
            var onDownMenu = function (e) {
                var target = e.target.d5component;
                if (target == Menu._nowDown)
                    return;
                var extdata = target.extdata;
                if (extdata && extdata.fun) {
                    extdata.fun.apply(extdata.thisobj, [extdata.data]);
                    return;
                }
                if (that._downMenu)
                    that._downMenu.dispose();
                var down = new MenuDown(that);
                down.setup(extdata);
                down.list.setPosition(that._hbox.x + target.x, that._hbox.y + target.y + target.height + 3);
                D5Power.addChild(down.list);
                that._downMenu = down;
                Menu._nowDown = target;
                birthTime = D5Power.getTimer();
            };
            var onResize = function (e) {
                that.asyncDraw();
            };
            for (var i = 0, j = conf.length; i < j; i++) {
                btn = new d5.D5HoverText(conf[i][0], this._fontColor, this._fontSize, 5);
                btn.setHover(this._hoverColor);
                btn.extdata = conf[i][1];
                btn.autoSize();
                btn.addEventListener(d5.TouchEvent.TOUCH_OVER, onMouseOver);
                btn.addEventListener(d5.TouchEvent.TOUCH_TAP, onDownMenu);
                this._hbox.addChild(btn);
            }
            window.addEventListener("resize", onResize);
            // 点击舞台自动关闭下拉菜单
            D5Power.stageOn(d5.TouchEvent.TOUCH_TAP, function (e) {
                var down = that._downMenu;
                if (!down)
                    return;
                var timeCheck = D5Power.getTimer() - birthTime;
                if (timeCheck < 60)
                    return;
                down.dispose();
                that.clearDown();
            });
        };
        return Menu;
    }(d5.D5Component));
    d5.Menu = Menu;
    __reflect(Menu.prototype, "d5.Menu");
    var MenuDown = (function () {
        function MenuDown(menu) {
            if (menu === void 0) { menu = null; }
            this._menu = menu;
        }
        MenuDown.prototype.dispose = function () {
            this._list.dispose();
            if (this._son)
                this._son.dispose();
            this._menu && this._menu.clearDown();
        };
        Object.defineProperty(MenuDown.prototype, "list", {
            get: function () {
                return this._list;
            },
            enumerable: true,
            configurable: true
        });
        MenuDown.prototype.setup = function (conf, listener) {
            if (listener === void 0) { listener = null; }
            if (this._list) {
                this._list.dispose();
            }
            var that = this;
            var checkSon = function (e) {
                var lab = e.target.d5component;
                if (that._son) {
                    that._son._list.dispose();
                    that._son = null;
                }
                if (lab.extdata == null || !lab.extdata.length)
                    return;
                var son = new MenuDown();
                son._belone = lab;
                son.setup(lab.extdata, onSelect);
                son.list.setPosition(that._list.width + 5, lab.y);
                that._list.addChild(son.list);
                that._son = son;
            };
            var onSelect = function (e) {
                var data = e.data;
                if (data && data.fun) {
                    data.fun.apply(data.thisobj, [data.data]);
                    that.dispose();
                }
            };
            this._list = new d5.D5List();
            this._list.leftPadding = 20;
            for (var i = 0, j = conf.length; i < j; i++) {
                var lab = this._list.addItem(conf[i][0], conf[i][1]);
                if (lab) {
                    lab.addEventListener(d5.TouchEvent.TOUCH_OVER, checkSon);
                }
            }
            this._list.addEventListener(d5.Event.SELECT, listener ? listener : onSelect);
        };
        return MenuDown;
    }());
    __reflect(MenuDown.prototype, "MenuDown");
})(d5 || (d5 = {}));
var App = (function () {
    function App() {
    }
    App.prototype.start = function () {
    };
    return App;
}());
__reflect(App.prototype, "App");
var d5;
(function (d5) {
    var AppIcon = (function (_super) {
        __extends(AppIcon, _super);
        function AppIcon() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(AppIcon.prototype, "width", {
            get: function () {
                return 52;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AppIcon.prototype, "height", {
            get: function () {
                return 100;
            },
            enumerable: true,
            configurable: true
        });
        return AppIcon;
    }(d5.DisplayContainer));
    __reflect(AppIcon.prototype, "AppIcon");
    var Desktop = (function (_super) {
        __extends(Desktop, _super);
        function Desktop(menus) {
            var _this = _super.call(this, 'resource/ui/5rpg/home.json') || this;
            _this._menus = menus;
            return _this;
        }
        Desktop.prototype.addMenus = function (menu) {
            this._menus.push(menu);
            this.updateMenus();
        };
        Desktop.prototype.updateMenus = function () {
            var menus = this._menus;
            var that = this;
            this.removeChildren();
            var _loop_1 = function (i, j) {
                var app_icon = this_1._app_icon_temp.getInstanceBind(AppIcon);
                app_icon.icon.setSkin(menus[i].icon);
                app_icon.label.text = menus[i].label;
                app_icon.ui = menus[i].ui;
                app_icon.x = this_1._startP.x;
                app_icon.y = this_1._startP.y + (i * app_icon.height + 20);
                app_icon.touchEnable = true;
                app_icon.addEventListener(d5.TouchEvent.TOUCH_TAP, function () {
                    that.dispathEvent(d5.Event.OPENUI, app_icon.ui);
                });
                this_1.addChild(app_icon);
            };
            var this_1 = this;
            for (var i = 0, j = menus.length; i < j; i++) {
                _loop_1(i, j);
            }
        };
        Desktop.prototype.onLoaded = function () {
            this._app_icon_temp = new d5.D5Template();
            this._startP = { x: this.icon.x, y: this.icon.y };
            this._app_icon_temp.fromComponent(this.icon, this.label);
            this.updateMenus();
        };
        return Desktop;
    }(d5.D5UI));
    d5.Desktop = Desktop;
    __reflect(Desktop.prototype, "d5.Desktop");
})(d5 || (d5 = {}));
var d5;
(function (d5) {
    /**
     * TTSAPI
     */
    //export const localapi:string = "http://192.168.3.3:5550/";
    //export const localapi: string = "http://14.103.154.65:5550/";
    d5.localapi = "http://127.0.0.1:5550/";
    d5.dispatchEvent = function (eventDispather, type, data) {
        if (data === void 0) { data = null; }
        var event = new CustomEvent(type, {
            detail: { data: data },
            bubbles: true,
            cancelable: true
        });
        eventDispather.dispatchEvent(event);
    };
    /**
     * 长文切分
     * @param text
     * @param len
     * @param minLeft
     * @returns
     */
    d5.splitSentences = function (text, len, minLeft) {
        if (len === void 0) { len = 60; }
        if (minLeft === void 0) { minLeft = 0.2; }
        text = text.replace(/\n/ig, '');
        var ending = /[。？！，,.?!]/;
        var sentences = [];
        var cache = '';
        for (var i = 0, j = text.length; i < j; i++) {
            var char = text.charAt(i);
            cache += char;
            if (cache.length >= len && ending.test(char)) {
                if (text.length - i < len * minLeft) {
                    cache += text.substring(i + 1);
                    break;
                }
                else {
                    sentences.push(cache);
                    cache = '';
                }
            }
        }
        if (cache)
            sentences.push(cache);
        return sentences;
    };
    /**
     * 支持音色标签的长文切分
     * @param text
     * @param len
     * @param minLeft
     * @returns
     */
    d5.splitSentences2 = function (text, len, minLeft) {
        if (len === void 0) { len = 60; }
        if (minLeft === void 0) { minLeft = 0.2; }
        text = text.replace(/\n/ig, '');
        var ending = /[。？！，,.?!]/;
        var sentences = [];
        var cache = '';
        var i = 0;
        var j = text.length;
        while (i < j) {
            var char = text.charAt(i);
            // 检查是否是标签开始
            if (char === '[') {
                // 如果cache中有内容，先处理cache
                if (cache) {
                    sentences.push(cache);
                    cache = '';
                }
                // 查找标签结束和引号开始的位置
                var tagEndIndex = -1;
                var quoteStartIndex = -1;
                for (var k = i + 1; k < j; k++) {
                    if (tagEndIndex === -1 && text.charAt(k) === ']') {
                        tagEndIndex = k;
                    }
                    else if (tagEndIndex !== -1 && (text.charAt(k) === '“' || text.charAt(k) === '"')) {
                        quoteStartIndex = k;
                        break;
                    }
                }
                // 如果找到了标签结束和引号开始
                if (tagEndIndex !== -1 && quoteStartIndex !== -1) {
                    // 查找引号结束的位置
                    var quoteEndIndex = -1;
                    var endQuoteChar = text.charAt(quoteStartIndex); // 记录是哪种引号
                    if (endQuoteChar == "“")
                        endQuoteChar = "”"; // 中文引号的配对出现
                    for (var k = quoteStartIndex + 1; k < j; k++) {
                        if (text.charAt(k) === endQuoteChar) {
                            quoteEndIndex = k;
                            break;
                        }
                    }
                    // 如果找到了引号结束，将整个标签引号内容作为一个句子
                    if (quoteEndIndex !== -1) {
                        var tagQuoteContent = text.substring(i, quoteEndIndex + 1);
                        sentences.push(tagQuoteContent);
                        i = quoteEndIndex + 1;
                        continue;
                    }
                }
            }
            // 原有逻辑：处理标点符号分割
            cache += char;
            if (cache.length >= len && ending.test(char)) {
                if (j - i < len * minLeft) {
                    cache += text.substring(i + 1);
                    break;
                }
                else {
                    sentences.push(cache);
                    cache = '';
                }
            }
            i++;
        }
        if (cache)
            sentences.push(cache);
        return sentences;
    };
    /**
     *
     * @param src
     * @param playCallback 当声音开始播放时触发
     * @param target
     * @returns
     */
    d5.playAudio = function (src, playCallback, target) {
        if (playCallback === void 0) { playCallback = null; }
        if (target === void 0) { target = null; }
        return new Promise(function (accept, reject) {
            if (accept === void 0) { accept = null; }
            if (reject === void 0) { reject = null; }
            var attemptCount = 0;
            var maxAttempts = 3;
            var onAudioEnded = function () {
                audio.removeEventListener('ended', onAudioEnded);
                audio.removeEventListener('error', onError);
                if (accept != null)
                    accept(audio);
            };
            var onAudioBegin = function () {
                audio.removeEventListener('playing', onAudioBegin);
                if (playCallback)
                    playCallback();
                playCallback = null;
            };
            var onError = function () {
                attemptCount++;
                if (attemptCount < maxAttempts) {
                    // 等待1秒后重新尝试
                    setTimeout(function () {
                        try {
                            audio.load(); // 重新加载音频
                            audio.play();
                        }
                        catch (e) {
                            // 如果再次出错，继续重试逻辑
                            onError();
                        }
                    }, 1000);
                }
                else {
                    // 3次尝试后仍然失败，调用onAudioEnded
                    onAudioEnded();
                }
            };
            var audio = target == null ? document.getElementById('myAudio') : document.getElementById('secAudio');
            if (!audio) {
                console.log("===Dom myAudio can not found to play audio ====" + src);
                return;
            }
            try {
                audio.src = src;
                audio.addEventListener('error', onError);
                audio.play();
                audio.addEventListener('ended', onAudioEnded);
                audio.addEventListener('playing', onAudioBegin);
            }
            catch (e) {
                // 初始播放出错时也触发重试逻辑
                onError();
            }
        });
    };
    /**
     * 加载一个HTML
     * @param address
     * @param container
     * @returns
     */
    d5.loadPage = function (address, container) {
        if (container === void 0) { container = null; }
        var $ = layui.$;
        return new Promise(function (resolve, reject) {
            $.get(address, function (res) {
                if (container != null) {
                    try {
                        $(container).html(res);
                    }
                    catch (e) {
                        console.log("[Error]===== loadPage error in " + address, " and container is " + container);
                    }
                }
                else {
                    resolve(res);
                }
            });
        });
    };
})(d5 || (d5 = {}));
